Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for jQuery AJAX response(s) [duplicate]

I have a page that, using jQuery .ajax that is called 100 times (async: true), the problem is that, when they they are all being loaded, I need the system to wait for ALL 100 calls to return before continuing. How would I go about this?

Thanks in advance! :)

Update:

These calls are made in a for() loop (there's 100 of them :))

like image 910
Olive Avatar asked Jun 06 '11 09:06

Olive


People also ask

How can you find out that an Ajax request has been completed?

To check if an AJAX request has been successfully completed, you need to use the ReadyState property. The request is completed when the property is equal to four.

Can we execute run multiple Ajax requests simultaneously in jQuery?

There is a requirement to make multiple AJAX calls parallelly to fetch the required data and each successive call depends on the data fetched in its prior call. Since AJAX is asynchronous, one cannot control the order of the calls to be executed.

Does Ajax wait for response?

ajax() function with the default settings, any JavaScript code after this AJAX request will be executed without waiting for a response. In most cases, this is the desired behavior, but there are some situations where you will want to prevent further execution until there has been a response to the AJAX call.

What is async true in Ajax call?

by default async is true. it means process will be continuing in jQuery ajax without wait of request. Async false means it will not go to next step untill the response will come.


1 Answers

The nice way to do this is with $.when. You can use this as follows:

$.when(
    $.ajax({/*settings*/}),
    $.ajax({/*settings*/}),
    $.ajax({/*settings*/}),
    $.ajax({/*settings*/}),
).then(function() {
    // when all AJAX requests are complete
});

Alternatively, if you have all the AJAX calls in an array, you could use apply:

$.when.apply($, ajaxReqs);

Note that this requires at least jQuery 1.5.


To add the AJAX requests to an array, do something like this:

var ajaxReqs = [];
for (var i = 0; i < 100; i++) {
    ajaxReqs.push($.ajax({
        /* AJAX settings */
    });
}
$.when.apply($, ajaxReqs).then(function() {
    // all requests are complete
});
like image 134
lonesomeday Avatar answered Nov 02 '22 17:11

lonesomeday