Executing multiple $.ajax Calls Before Firing Success

By November 15, 2014 Blog No Comments

If you have done any kind of web development you will have likely made some asynchronous calls to an API or some kind of back end. In jQuery we will use the $.ajax() method to make these calls. With this call we can pass in all sorts of parameters and typically fire either a success or error callback. But what if we want to fire two or more ajax calls before firing a callback.

Fortunately jQuery allows us to do this quite easily with a variety of methods. For now we will just take a look at the $.when method to solve this problem. All we need to do is pass it multiple ajax requests and it will wait until both return “success” and then it will fire.

$.when($.ajax('/page1.php'), $.ajax('/page2.php')).done(function(resp1, resp2) {
  console.log(resp1);
  console.log(resp2);
});

The response data will be returned in the same order as your ajax calls and from there you can do whatever needs to be done with those responses.

If there are errors then this success function will NOT call. Instead the error functions from the separate ajax calls will fire and then processing will stop.

Of course we can also move the ajax calls into there own functions to clean things up a little.

function one() {
  return $.ajax('/page1.php');
}

function two() {
  return $.ajax('/page2.php');
}

$.when(one(), two()).done(function(resp1, resp2) {
  console.log(resp1);
  console.log(resp2);
});

That cleans things up a little especially since our ajax calls will usually contain a lot more input than just a path. The nice thing here really is that we don’t have to have a series of nested callbacks with $.ajax calls within $.ajax calls. This can get really messy and hard to read. Having it separate makes it much clearer to see what is going on.