Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel asynchronous Ajax requests using jQuery

I'd like to update a page based upon the results of multiple ajax/json requests. Using jQuery, I can "chain" the callbacks, like this very simple stripped down example:

$.getJSON("/values/1", function(data) {   // data = {value: 1}   var value_1 = data.value;    $.getJSON("/values/2", function(data) {     // data = {value: 42}     var value_2 = data.value;      var sum = value_1 + value_2;      $('#mynode').html(sum);   });  }); 

However, this results in the requests being made serially. I'd much rather a way to make the requests in parallel, and perform the page update after all are complete. Is there any way to do this?

like image 549
Paul Avatar asked Jun 29 '09 21:06

Paul


People also ask

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.

Is jQuery AJAX asynchronous?

The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.

Can we call two AJAX inside AJAX?

Function ajax can only make one Ajax call. A callback function is executed when the Ajax call is successful. Optionally, another callback function is called when the Ajax call returns an error.

Can AJAX requests be made synchronous?

AJAX can access the server both synchronously and asynchronously: Synchronously, in which the script stops and waits for the server to send back a reply before continuing. Asynchronously, in which the script allows the page to continue to be processed and handles the reply if and when it arrives.


2 Answers

jQuery $.when() and $.done() are exactly what you need:

$.when($.ajax("/page1.php"), $.ajax("/page2.php"))   .then(myFunc, myFailure); 
like image 128
Yair Leviel Avatar answered Oct 02 '22 12:10

Yair Leviel


Try this solution, which can support any specific number of parallel queries:

var done = 4; // number of total requests var sum = 0;  /* Normal loops don't create a new scope */ $([1,2,3,4,5]).each(function() {   var number = this;   $.getJSON("/values/" + number, function(data) {     sum += data.value;     done -= 1;     if(done == 0) $("#mynode").html(sum);   }); }); 
like image 33
Yehuda Katz Avatar answered Oct 02 '22 11:10

Yehuda Katz