How to call alert after all ajax requests are done?

I'm making in code a few requests with JQuery and get. It looks like:

$.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 detect whether there is still processing request and run marked code only when all 3 requests are finished.

Thanks.

Answers:

Answer

You can make use of deferred objects [docs] introduced in jQuery 1.5:

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

Reference: jQuery.when

The jQuery learning center has a nice introduction to deferred objects / promises.

Answer
 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');
};
Answer
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');
  }
}
Answer
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);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.