Last Updated: February 25, 2016
·
3.001K
· ihcsim

JQuery Multiple AJAX Calls Using when/then

(Tested on http://jsfiddle.net/ivan_sim/SGeA6/)

$(document).ready(function() {
  var dataSet1 = {
    val: "First echo response"
  };
  var dataSet2 = {
    val: "Second echo response"
  };

   $.when(
     $.getJSON("/echo/jsonp", dataSet1), 
     $.getJSON("/echo/jsonp", dataSet2)
     .error(function(jqXHR, textStatus, errorThrown) {
       console.log("Encounter error " + textStatus + ". " + errorThrown);
     }))
   .then(function(firstResponse, secondResponse) {
     $("#output").append(firstResponse[0].val + ". " + secondResponse[0].val);
  });
});​