0

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

Edit:

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");
    });
}
Community
  • 1
  • 1
  • Store a counter which gets incremented within the `done` callback. When it hits 6, execute your function. – Rory McCrossan Sep 12 '16 at 11:55
  • @Igor It doesn't need to be a global counter, it can be local. –  Sep 12 '16 at 11:58
  • I have alredy tried that too, it seems to make sense but that function I have to call after all the ajax request have to compress in a .rar all the csv created before and im getting an error in the last call despite that all files are added correctly – Lucas Randisi Sep 12 '16 at 12:04
  • Possible duplicate of [jQuery callback for multiple ajax calls](http://stackoverflow.com/questions/4368946/jquery-callback-for-multiple-ajax-calls) – Mike Scotty Sep 12 '16 at 12:10

2 Answers2

2

$.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.

Joseph
  • 117,725
  • 30
  • 181
  • 234
0

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
});
xxxmatko
  • 4,017
  • 2
  • 17
  • 24