1

I'm doing 3 asynchronous ajax requests.

Afterwards I need a function executed but only if all 3 requests have finished.

How would I accomplish that?

Due to our framework, I'm limited to the latest 1.4 release.

Thanks, Wesley

4 Answers4

2

You need to have all the response handlers call the same scope/function, and keep track of the returned requests there. Only move on if all requests return. Don't forget to handle error cases.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
0

Expanding on Andrius's answer, I do something similar to his all the time:

function f1(){
  $.ajax({
    url: "test.html",
    success: function(data){
      //do something
      f2();
    }
  });
}

function f2(){
  $.ajax({
    url: "test2.html",
    success: function(data){
      //do something else
      //maybe call f1() if you want to loop again?
    }
  });
}

I chain together many calls this way. Sometimes I put setTimeout(function(){f2()},1000); If I want to have a slight pause between calls.

And my application requires constant polling from the server, so I have my last one in the chain call the first one. So it will loop forever with only one current call outstanding (so I don't hammer the server with requests)

Landon
  • 4,088
  • 3
  • 28
  • 42
0

You can achieve it with Reactive Extension for jQuery. Have a look at this question: trigger event after several ajax calls succeeded

Community
  • 1
  • 1
Giorgi
  • 30,270
  • 13
  • 89
  • 125
0

The simplest and a very limited way would be just to nest your ajax calls. But that only works if you make those calls at the same time in the same place.

$.ajax({
  url: "test.html",
  success: function(){
    $.ajax({
      url: "test2.html",
      success: function(){
        // n level nesting
      }
    });
  }
});
  • 1
    That's synchronous and will slow down the loading of these ajax requests as they're done 1 by 1. –  Aug 03 '11 at 15:39
  • 1
    @Wesley no, that's not "synchronous", it's "serialised". Each call here is technically _asynchronous_, but the next one isn't triggered until the previous one has completed. – Alnitak Jan 12 '12 at 23:26