How to trigger a warning after all ajax requests are completed?

I make several queries in the code using jQuery and get. It looks like this:

$.get('address1', function() { ... });
$.get('address2', function() { ... });
$.get('address3', function() { ... });

// This code should be runned when all 3 requests are finished
alert('Finished');

So, are there any ways to determine if there is another processing request and run the marked code only when all 3 requests are complete.

Thank.

+5
source share
4 answers

You can use pending objects [docs] introduced in jQuery 1.5:

$.when(
    $.get('address1', function() { ... }),
    $.get('address2', function() { ... }),
    $.get('address3', function() { ... })
).then(function() {
    alert('Finished');
});

Link: jQuery.when

The jQuery Learning Center has a nice introduction to deferred objects / promises .

+13
source
 var isFinished = [];

$.get('address1', function() { isFinshed.push["address1"]; allDone(); });
$.get('address2', function() { isFinshed.push["address2"]; allDone(); });
$.get('address3', function() { isFinshed.push["address3"]; allDone();});

var allDone = function(){
    if(isFinished.length < 3)return

    alert('Finished');
};
+2
source
var fin1 = false;
var fin2 = false;
var fin3 = false;

$.ajax({
  url: "address1",
  success: function(){
    fin1 = true;
    fnUpdate();
  }
});

$.ajax({
  url: "address2",
  success: function(){
    fin2 = true;
    fnUpdate();
  }
});

$.ajax({
  url: "address3",
  success: function(){
    fin3 = true;
    fnUpdate();
  }
});

function fnUpdate(){
  if(fin1 && fin2 && fin3){
    alert('fin');
  }
}
0
var count = 0;
$.get('address1', function() { count++; ... });
$.get('address2', function() { count++; ... });
$.get('address3', function() { count++; ... });

var int = setInterval(function() {
    if (count === 3) {
        clearInterval(int);
        alert('done');
    }
}, 10);
0

All Articles