Lothre1
Lothre1

Reputation: 3853

How to create a centralized callback for multiple ajax requests?

I would like to be able to send multiple ajax requests and merge all the responses in a single callback, how can i do that without mess with callbacks inside each request?

Instead of a system like this -> send ajax1 on ajax1 success -> send ajax2 on ajax2 success process both answer and render a view

I would like to be able to request ajax1 and ajax2

call ajax1
call ajax2

> when both are finished

process answer from both requests in a single function

callback (response_ajax1, response_ajax2 ) {
    // process information
}

Upvotes: 0

Views: 682

Answers (1)

Lothre1
Lothre1

Reputation: 3853

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/

Upvotes: 1

Related Questions