Can we execute/run multiple Ajax request simultaneously in jQuery? If yes, then how?

Technology CommunityCategory: jQueryCan we execute/run multiple Ajax request simultaneously in jQuery? If yes, then how?
VietMX Staff asked 3 years ago
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? Could you refactor this code?

Yes, it is possible to execute multiple Ajax request simultaneously or in parallel. Instead of waiting for 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 request simultaneously. Using jQuery .when() method which provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.

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

$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
      .then(myFunc, myFailure);