Introduction
Yesterday for one of my requirements, I needed to execute/run multiple Ajax requests simultaneously or in parallel. Waiting for the first Ajax request to complete and then issue the second request is time consuming. The better approach to speed up things would be to execute multiple Ajax requests simultaneously.
Related Posts
To do this, we can use jQuery
.when()
. The
$.when()
provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.
To show how it works, we will send multiple Ajax requests to Flickr API to fetch some photos. The first request will fetch photos which are tagged with "moon
" and the second request will fetch photos tagged with "bird
". And then, we display the results in a div
of both the requests.
The basic syntax is:
$.when(request1, request2, request3.....)
So here are 2 ajax requests to flickr API. To iterate through the response, there is a callback function attached to it. This callback function gets executed once both the Ajax requests are finished.
In case where multiple Deferred objects are passed to $.when()
, it takes the response returned by both calls, and constructs a new promise object. The res1
and res2
arguments of the callback are arrays, where res1
has response of the first request and res2
has response from the second request.
$(document).ready(function () {
$.when($.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "moon",
tagmode: "any",
format: "json"
}),
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "bird",
tagmode: "any",
format: "json"
})).then(function (res1, res2) {
$.each(res1[0].items, function (i, item) {
var img = $("<img/>");
img.attr('width', '200px');
img.attr('height', '150px');
img.attr("src", item.media.m).appendTo("#dvImages");
if (i == 3) return false;
})
$.each(res2[0].items, function (i, item) {
var img = $("<img/>");
img.attr('width', '200px');
img.attr('height', '150px');
img.attr("src", item.media.m).appendTo("#dvImages");
if (i == 3) return false;
})
});
});
See complete code here.
You can also declare what to do in case of success and failure of Ajax request. The below jQuery code executes the function myFunc
when both Ajax requests are successful, or myFailure
if either one has an error.
$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
.then(myFunc, myFailure);
Read more about $.when.
Feel free to contact me for any help related to jQuery. I will gladly help you.CodeProject