Waiting for jQuery AJAX response(s)

Eax picture Eax · Jun 6, 2011 · Viewed 25.1k times · Source

I have a page that, using jQuery .ajax that is called 100 times (async: true), the problem is that, when they they are all being loaded, I need the system to wait for ALL 100 calls to return before continuing. How would I go about this?

Thanks in advance! :)

Update:

These calls are made in a for() loop (there's 100 of them :))

Answer

lonesomeday picture lonesomeday · Jun 6, 2011

The nice way to do this is with $.when. You can use this as follows:

$.when(
    $.ajax({/*settings*/}),
    $.ajax({/*settings*/}),
    $.ajax({/*settings*/}),
    $.ajax({/*settings*/}),
).then(function() {
    // when all AJAX requests are complete
});

Alternatively, if you have all the AJAX calls in an array, you could use apply:

$.when.apply($, ajaxReqs);

Note that this requires at least jQuery 1.5.


To add the AJAX requests to an array, do something like this:

var ajaxReqs = [];
for (var i = 0; i < 100; i++) {
    ajaxReqs.push($.ajax({
        /* AJAX settings */
    });
}
$.when.apply($, ajaxReqs).then(function() {
    // all requests are complete
});