Parallel asynchronous Ajax requests using jQuery
ajax, javascript, jquery
Solution
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);
});
});
Problem
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?