the railslearner
the railslearner

Reputation: 101

How do I know when all AJAX calls from a particular functions are finished?

I have a function which has many different function calls having many ajax calls inside. How do I know if all the ajax calls being triggered by $("#save").click(...) are completed ?

$("#save").click(function() {

    saveUpdateSeatDetails();
    markAbsent();

    setTimeout(function() {
        location.reload();
    }, 369);
});

I tried using async: false, but I get warring suggesting it's deprecated.

I also referred How to know when all ajax calls are complete ?. However, this applies for the entire page. I want this to apply on a particular function only.

(Nothing ES6 )

Upvotes: 2

Views: 78

Answers (1)

Richard Ye
Richard Ye

Reputation: 695

You should jQuery's Deferred (slightly different but mostly compatible with Promises), which is returned by $.ajax calls. I'm going to assume you're using $.ajax here since you used jQuery in your answer.

You'll need to update your functions to return the $.ajax calls:

function saveUpdateSeatDetails() {
    return $.ajax("http://example.com...");
}

function markAbsent() {
    return $.ajax("http://example.com...");
}

Then you can do:

$("#save").click(function() {
    $.when(saveUpdateSeatDetails(), markAbsent()).done(function() {
         alert("test")
    });
});

$.when waits for the Ajax requests to complete before executing the function.

Since this is part of jQuery 1.5+, any browser compatible with jQuery will be able to run this code (no ES6 needed).

Upvotes: 5

Related Questions