tags:

views:

31

answers:

3

Hi,

I'm calling several ajax search services with jQuery and would like to trigger a function that merges the results when all the calls are finished (some kind of callback function waiting for all callbacks to have returned). What's the best method to achieve that?

thanks

jul

A: 

I would probably use the ajaxComplete event. You'll have to have your own logic for knowing when the series starts and finishes, but that presumably will come out of your application logic anyway.

Here's a trivial example (live copy):

jQuery(function($) {
  var count = 0;

  display("Hooking up handler");
  $(document.body).ajaxComplete(function(event, xhr, options) {
    ++count;
    display("Got a completion, new counter value = " + count);
  });
  display("Doing three ajax requests.");
  $.ajax({
    url: "http://jsbin.com/aciyu4"
  });
  $.ajax({
    url: "http://jsbin.com/aciyu4"
  });
  $.ajax({
    url: "http://jsbin.com/aciyu4"
  });

  function display(msg) {
    $("<p/>").html(msg).appendTo(document.body);
  }
});​

In that example, I'm keeping track of how many requests have completed using a count variable over which the registered handler is a closure (and so has access to it).

T.J. Crowder
A: 

Increase a local variable when making an ajax call. Decrease it on the return callback. When one callback triggers the var back to 0, call the global result callback. You can alternatively use an array of calls you made, or a stack, etc...

samy
+1  A: 

One method I've seen used in the past is a counter:

var counter = 3;

$.ajax({
  // ..
  success: function() {
    if(--counter == 0) handleComplete();
    // ...
  }
});

// 2 other similar ajax calls here

function handleComplete() {
  // this is done when all are complete
}

Obviously, you'll want to handle errors too.

sje397