Assuming I have the following:
function main() {
var finished = false;
for(var i=0; i < 3; i++) {
do(i);
}
}
function do(i) {
$.ajax({
url:"myurl.com/"+i,
datatype:"text/xml",
success: function() {
// Two more layers of multiple nested $.ajax elements here
}
})
}
Is there some way I could pop an alert box after all the "do" are finished after the three iterations? How? Syntax would help.
An ajax call returns a jQuery Promise object. You could collect the output of each one in an array, and use $.when
to 'bundle' the promises together.
This code is the basic idea behind what you want:
function main() {
var finished = false;
var defs = [];
for(var i=0; i < 3; i++) {
defs.push(do(i));
}
$.when.apply(null, defs).done(function() {
//this code will only run when all ajax calls are complete
});
}
function do(i) {
var promise = $.ajax({
url:"myurl.com/"+i,
datatype:"text/xml",
success: function() {
// Two more layers of multiple nested $.ajax elements here
}
})
return promise;
}
The browser can have a lot of open HTTP connections, don't let the naysayers convince you otherwise. Here is a table of maximum concurrent connections supported by browser. Let your site usage statistics be your guide, but even 2 ajax requests at once is faster than totally synchronous data requests...
Firefox 2: 2
Firefox 3+: 6
Opera 9.26: 4
Opera 12: 6
Safari 3: 4
Safari 5: 6
IE 7: 2
IE 8: 6
IE 10: 8
Chrome: 6
As global:
var complete = 0;
All AJAX calls;
$.ajax({
... //other attributes,
complete: function(){
complete++;
if (complete == 3) {
alert('all completed');
}
}
});
This would execute when three AJAX calls are done. However, if you need to increase it, then do so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With