Dan Inactive
Dan Inactive

Reputation: 10070

jquery ajax: call function when all requests are complete

I have two concurrent ajax calls on the page. I want to call a function when both of them are complete (and successful).

An inefficient solution:

  1. make ajax call A
  2. on success for call A, make call B
  3. on success for call B, call the function

Unfortunately, this breaks the concurrency.

Any other way I can accomplish the same effect?

Upvotes: 2

Views: 1662

Answers (4)

LazyZebra
LazyZebra

Reputation: 1113

$(document).ajaxStop(function() {
        //do your JQuery stuff;
});

Upvotes: 1

NickFitz
NickFitz

Reputation: 35091

Have a look at this answer I gave to pretty much the same question the other day, and also have a look at the demo I created to go with it (view source on that page to see the complete code). It makes much more efficient use of JavaScript's inherent capabilities and overall nature as a language than mucking about with flag variables, IMHO ;-)

Upvotes: 1

Jarrett Meyer
Jarrett Meyer

Reputation: 19593

var isASuccessful = false;
var isBSuccessful = false;
function callARequest() {
    $.get("path/to/url", { params: list }, function() {
        isASuccessful = true;
        if (isBSuccessful) {
            callMeAfterAandB();
        } else {
            callBRequest();
        }
    });
}
function callBRequest() {
    $.get("path/to/other/url", { params: list }, function() {
        isBSuccessful = true;
        if (isASuccessful) {
            callMeAfterAandB();
        } else {
            callARequest();
        }
    });
}
function callMeAfterAandB() {
    // todo: something
}

Upvotes: 0

Neeraj Singh
Neeraj Singh

Reputation: 2146

set a global variable ajax_call_A_complete set another global varialbe ajax_call_B_complete set these two varialbes to false

No make ajax calls concurrently. In the success callback of both the ajax calls set the varialbes to true. I mean ajax call A will set ajax_call_A_complete to true and ajax call B will set varialbe ajax_call_B_complete to true.

Set a periodic time which is checking the value of these two variables every 2 seconds. When both the variables are true then fire off your dependent task.

Upvotes: -1

Related Questions