0

Possible Duplicate:
Sequencing ajax requests

I got an array of artist names. For each artist name i make an ajax json call to a webservice to get songs by this artist.

My question now is: How can i be sure, that all ajax requests are done (either success or fail).

I looked at Deferreds and AjaxManager, but i cant implement it so that it runs (if it's the right method...)

My code looks something like:

$.each(tf.suggestedArtists, function(index, artist){
  var url = tf.enBaseUrl + "song/search?api_key=" + tf.apiKey + "&format=json&artist=" + artist.name + "&bucket=id:spotify-WW&bucket=tracks"

  $.ajax({
    type: "GET",
    url: url,
    dataType: 'json',
  }).done(function( data ) {
    //...do some more stuff

It's not possible to do these calls async because of JSON and cross domain issues.

Community
  • 1
  • 1
agrT
  • 225
  • 1
  • 2
  • 11

1 Answers1

1

If you want to be sure that all ajax requests are completed, you can use an if statement, and $.active,.

if($.active > 0){ 
  //There's an ajax request pending.
}else{
  //No ajax requests pending.
}
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
  • Nice one, didn't knwow about that. And it works for jQuery Ajax calls. The next Problem ist, that in each of my ajax calls, i got another asynchronous call from another library. but i think that's another question... – agrT Jul 31 '12 at 14:38
  • @AndreasGeibert Yeah. $.active *is not documented*, but it's exposed in the jQuery API, so it's easy enough to find and use. You got another Asynchronous call from another library? Why not save yourself the headache and utilize only 1 library. There's almost never any reason to use things like mootools + jquery, or scriptaculous + jquery, or mootools + scriptaculous...stick to 1, and utilize it, it's a safer bet. – Ohgodwhy Jul 31 '12 at 14:44
  • no, sorry i wrote that wrong: in my ajax call i call the spotify api via the spotify library. no other javascript framework/lib. and that spotify call is also asynchronous... – agrT Jul 31 '12 at 14:51
  • @Andreas Geibert This will detect any ajax calls. if it's getJSON...ajax....post...doesn't matter, they're all just psuedo-wrappers for jQuery's ajax. Any XHR request that's running will be detected with `$.active`. – Ohgodwhy Aug 01 '12 at 14:27