Jay Ocean
Jay Ocean

Reputation: 273

Populate html dynamically as backend runs in Flask

I am looking to dynamically populate results using flask and jQuery.

I have a program that runs a long series of tasks in a backend function appends the results to a list. Is there a way through ajax/jquery to dynamically add results to the page (say every few seconds) until the backend has finished running (Almost how a website like Travelocity dynamically adds flights to the page as it finds them). Currently, I cannot understand how to update results using ajax while the backend is still running (it waits until it is complete before returning any results).

My hypothetical example:

    $.ajax({
        url: '/test',
        type: 'post',
        data: 'Begin Running Backend',
        dataType: 'json',
        success: function(data) {
             while(**BACKEND IS RUNNING**){
                    $("#samplediv").text(data.current_results);
                   }
                },
        error: function(data) {
            console.log("FAILED");
        }
     }); 

While in the backend:

@app.route("/test",methods=['GET','POST'])
def test():
    run_script() #In this script, a for loop is adding results to a list
    return jsonify(results=list)

Upvotes: 1

Views: 336

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50798

Your while loop is not necessary here, as you will not receive a success callback until the server responds favorably.

The biggest issue you may be encoutering, however, is a possible timeout due to the long response time:

You can add the following to give it up to 1 minutes:

timeout: 60000

Then in your success function, start with logging out the results:

success: function (data) {
    console.log(data);
}

You do not need to pause the client side in this way with a while loop.

Upvotes: 1

Related Questions