According to jquery, since it's version 1.5 we can use Deferred objects for this.
What's a deferred object?:
[...] deferreds can be thought of as a way to represent asynchronous (not realtime)
operations which can take a long time to complete (ajax requests are
one of thoose examples).
-
Deferred objects are the asynchronous alternative to blocking functions and the
general idea is that rather than your application blocking while it
awaits some request to complete before returning a result.
-
[...] a deferred object can instead be returned immediately.
As summary:
Deferred objects provides a way to register multiple callbacks into self-managed
callback queues, invoke callback queues as appropriate, and relay the
success or failure state of any synchronous or asynchronous function..
To answer the question:
http://jsfiddle.net/mreis1/DCmrN/
function _ajax(id){
return $.ajax({
url: '/echo/json/',
type: 'GET',
dataType: 'json',
data: {param1: id},
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//console.log(data)
//called when successful
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});
}
// merge response data from both ajax calls when they are done
$.when( _ajax(1), _ajax(2) ).done(function(a1, a2){
console.log(a1, a2);
});
DOCUMENTATION
http://api.jquery.com/category/deferred-object/
SIMILAR PROBLEMS
http://forum.jquery.com/topic/using-when-to-deal-with-response-of-multiple-ajax-calls-deferred-objects
ARTICLES TO EXPLORE
http://www.tentonaxe.com/index.cfm/2011/9/22/Using-jQuerywhen-with-a-dynamic-number-of-objects
http://learn.jquery.com/code-organization/deferreds/
http://learn.jquery.com/code-organization/deferreds/examples/