You may need to run certain code only after all Ajax requests have completed when working with many Ajax requests. To do this, use the when function in jQuery.
$.when in JQuery
It takes any number of arguments and executes once all of the parameter functions have been performed.
If you have three Ajax requests and wish to wait for all three to complete, use the code below:
$.when(ajax1(), ajax2(), ajax3()).done(function(resp1, resp2, resp3) {
// the code here will be executed when all four ajax requests resolve.
console.log('All 3 ajax request complete.');
});
function ajax1() {
return $.ajax({
url: url1,
dataType: "json",
data: jsonRequestData1,
...
});
}
function ajax2() {
return $.ajax({
url: url2,
dataType: "json",
data: jsonRequestData2,
...
});
}
function ajax3() {
return $.ajax({
url: url3,
dataType: "json",
data: jsonRequestData3,
...
});
}