Reputation: 9842
I have three ajax calls which can run concurrently. However I want the browser to wait until all ajax calls completed. One way is to set async as false for each of them but then I lose precious time since they can run concurrently. Is there a way to run them concurrently but make the browser hangs until all completed?
Upvotes: 0
Views: 136
Reputation: 2184
You could do this using deferred objects, because ajax itself returns that object. Please refer to Pass in an array of Deferreds to $.when()
var deferreds = [
$.post(),
$.get(),
];
$.when.apply($, deferreds).done(function() {
// All ajax requests was done
});
Upvotes: 0
Reputation: 4592
To make work with asynchronous stuff easier, you can use the promises pattern. If you're on jQuery, you can use jQuery.when()
. From the docs:
$.when( $.ajax( "/p1.php" ), $.ajax( "/p2.php" )).done(function( a1, a2 ) {
//do this when both ajax calls are done
});
Upvotes: 0
Reputation: 8041
If you are using jQuery then have a look at $.when
, you can provide a success callback which gets executed when all the requests are finished loading.
Upvotes: 0
Reputation: 43441
After success, call callback function:
$.ajax({
success: function(){ checkAjax(); }
});
And in callback function count how much responses you have.
var totalEnded = 0, totalAjax = 3;
function checkAjax() {
totalEnded++;
if (totalEnded == totalAjax) {
/* Do important stuff here, or call another function */
}
}
Upvotes: 1