Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when processing is finished for multiple ajax calls in javascript?

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.

like image 901
Rolando Avatar asked Apr 03 '13 22:04

Rolando


2 Answers

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
like image 76
Alex Mcp Avatar answered Sep 22 '22 20:09

Alex Mcp


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.

like image 34
Justice Erolin Avatar answered Sep 24 '22 20:09

Justice Erolin