How to add a loading gif to the page when a function runs in the background in Flask?

Question:

I have written a Flask app that displays a page with a button, when the user clicks on that button a Python function is called which does some processing (which usually takes about 2 minutes). After this processing is over, a new page opens displaying the results. Now I want to include a ‘loading gif’ that indicates the user that the processing is in progress. How do I do this? Here is an example of what my code looks like.

app.py

from flask import Flask, render_template
 import time

 app = Flask(__name__)

 @app.route('/')
 def index():
     return render_template('index.html')

 @app.route('/result', methods=['POST'])
 def result():
     time.sleep(5) # indicates the time delay caused due to processing
     return render_template('result.html')

 if __name__ == '__main__':
     app.run(debug=True)

index.html

<html>
    <body>
        <form method=post action="/result">
            <input type=submit value='Start Processing' name='submit_btn'>
        </form>
    </body>
</html>

result.html

<html>
    <body>
        <h1> Processing Done </h1>
    </body>
</html>
Asked By: Harshith Bolar

||

Answers:

This needs to be done on the client side only.

Add jquery in your header section:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

Add this to your submit button code:

onclick="$('#loading').show();"

Get a loading.gif image Add below code after your form in html

<div id="loading" style="display:none;"><img src="loading.gif" alt="" />Loading!</div>

References:
1 2

Answered By: Priyank Mehta

The above code works, but you may consider using: onsubmit="$('#loading').show();" inside of the form element in the place of:

onclick="$('#loading').show();"

This will ensure that the loading animation is only displayed once your form is successfully submitted. Something like a required field could prevent the submission from going through, but with the listener being "on click", you will still display the loading gif, which may confuse your users.

Answered By: jeff's dad
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.