Reputation: 5
Im trying to execute a function after 6 ajax calls (indluding the ".done" part after each one)
function showReports(array_monitor){
$.ajax({
method: "GET",
url: array_monitor[0],
datatype: "text",
}).done(function(xml) {
monitorName = array_monitor[1];
convert(xml, monitorName);
});
};
I have tried with $.when but it seems that is not working as I wanted
I've included a global counter and the function after all the calls have to compress some files that are created, is it neccesary to set a timeout to wait or is $.when enough?
function zipAll(){
$.ajax({
method: "POST",
url: "zipAll.php",
}).done(function(){
window.location = "uptimeReports.zip";
console.log("hola");
});
}
Upvotes: 0
Views: 66
Reputation: 4142
You can use jQuery method $.when
. Each jQuery ajax call returns promise, and when you call $.when
on all these promises your callback will be called after all of these promises are resolved:
var xhr1 = $.ajax({ dataType: "json", url: '' });
var xhr2 = $.ajax({ dataType: "json", url: '' });
// etc ...
$.when(xhr1, xhr2, ...).then(function(xhr1Result, xhr2Result, ...) {
// You've got your results
});
Upvotes: 0
Reputation: 119827
$.ajax
returns a promise-like object. You feed that (all 6 of those) to $.when
. Also, don't use .done
but .then
for the sake of consistency since promises use .then
function showReports(array_monitor){
return $.ajax(...).then(function(xml){
// Do some parsing
return finalValue;
});
}
$.when.apply(null, [
showReports(...),
showReports(...),
showReports(...),
showReports(...),
showReports(...),
showReports(...),
]).then(function(result1, result2,...){
// All done
});
Also ensure that you return a value from showReports
's .then
callback. It's the resolved value for the promise, that becomes the value passed into $.when
.
Upvotes: 2