Skip to content Skip to sidebar Skip to footer

How To Get Jquery To Append Output Immediately After Each Ajax Call In A Loop

I'd like to append to an element and have it update immediately. console.log() shows the data as expected but append() does nothing until the for loop has finished and then writes

Solution 1:

If you switch to async: true, then the screen will be able to update as you append data.

$(document).ready(function() {
    var cntr = 0;
    // run 5 consecutive ajax calls// when the first one finishes, run the second one and so onfunctionnext() {
        $.ajax({
            async: true,
            url: 'server.php',
            success: function(r) {
                console.log(r); //this works
                $('#Data').append(r); //this happens all at once
                ++cntr;
                if (cntr < 5) {
                    next();
                }

            }
        });
    }
    next();
});

If you insist on using async: false (which is generally horrible), then you could put a short setTimeout() between each ajax call and the screen would update during the timeout.

There are also some hacks that "may" cause the screen to update (no guarantees) by accessing certain CSS properties that can only be calculated when the HTML layout is up-to-date which may causes the browser to display the latest changes. I say "may" because this is not by specification, only an observation of behavior in some browsers. You can read more about this option here.

In any case, since you're already using ajax calls, the best way to solve this here is to use async: true and change your loop construct to one that will work with the async ajax call (as I've shown in my example).

Post a Comment for "How To Get Jquery To Append Output Immediately After Each Ajax Call In A Loop"