0

I have a javascript function.Inside this function i have 3 ajax calls. How can i make sure that my another function executes after these ajax calls done?

function a(){
    for(var i=0;i<3;i++)
        $.post("somePage.php").done(function(){
            do stuff here...
        });
    return false;
}
function b(){
    //.....
}

will my function b execute after ajax calls done?

Tricky12
  • 6,752
  • 1
  • 27
  • 35
Mehman Manafov
  • 449
  • 1
  • 4
  • 8

3 Answers3

3

a complete solution will be something like

function a() {
    var array = [], xhr;
    for (var i = 0; i < 3; i++) {
        xhr = $.post("somePage.php").done(function () {});
        array.push(xhr)
    }
    //create a promise which will be called after all the ajax request are completed
    return $.when.apply($, array);
}

function b() {
    //.....
}

//on succss callback of all the ajax requests created in a call b
a().done(b)
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

Write an increment check which increments on each returned Ajax like below:

increments = 0;
$.post("somePage.php").done(function(){
  // Check if the increments are total to 3
  ++increments;
  if(increments == 3) {
    //do something now such as call b();
  }
  //do stuff here...
});
Rob Schmuecker
  • 8,934
  • 2
  • 18
  • 34
0

The jQuery ajaxStop method allows you to register a handler to be called when all Ajax requests have completed.

Christophe
  • 27,383
  • 28
  • 97
  • 140