Wait until All Jquery Ajax Requests Are Done?

Solution 1: Using $.when().then()

In this solution, we use the <code>$.when()</code> method to wait for multiple Ajax requests to complete.
The <code>$.when()</code> method takes one or more Deferred objects as arguments and returns a new Deferred object that
waits for all the Deferred objects to be resolved or rejected.
We can then use the <code>.then()</code> method to handle the responses once all the requests are done.



Here's an example code snippet:
function waitUntilAllRequestsAreDone1() {
    var request1 = $.ajax({
        url: "https://api.example.com/data1",
        method: "GET"
    });

    var request2 = $.ajax({
        url: "https://api.example.com/data2",
        method: "GET"
    });

    $.when(request1, request2).then(function(response1, response2) {
        // Handle the responses here
        var data1 = response1[0];
        var data2 = response2[0];
        console.log(data1);
        console.log(data2);
    });
}

Solution 2: Using $.ajaxStop()

Another approach is to use the <code>$.ajaxStop()</code> method.
This method registers a handler to be called when all Ajax requests have completed.
It is triggered when the number of active Ajax requests becomes zero.
We can then handle the responses inside the <code>$.ajaxStop()</code> callback function.



Here's an example code snippet:
function waitUntilAllRequestsAreDone2() {
    var request1 = $.ajax({
        url: "https://api.example.com/data1",
        method: "GET"
    });

    var request2 = $.ajax({
        url: "https://api.example.com/data2",
        method: "GET"
    });

    $(document).ajaxStop(function() {
        // Handle the responses here
        var data1 = request1.responseText;
        var data2 = request2.responseText;
        console.log(data1);
        console.log(data2);
    });
}
Now you have two solutions to wait until all jQuery Ajax requests are done.
Choose the one that suits your needs and implement it in your JavaScript code.

Posted

in

, , ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *