riciloma
riciloma

Reputation: 1844

Weird AJAX behaviour with loops

I've got a pair of nested AJAX request that do not behave correctly. The first gets a list of albums, and the second one gets executed for every album, giving me a list of tracks.

$.ajax({
    url:getPHPSite(),
    method:"POST",  
    data:{
        query: "SELECT id_album FROM albums;"
    },
    success: function(response){
      var albums=JSON.parse(response);
      for(var i=0; i<albums.length;i++){
          var albumID=albums[i]['id_album'];
             getTracks(function(courses) {
              //do something
            }
            }, albumID);


        }  
    }, ....//error handler and everything else

The getTracks() function actually performs the second AJAX request and returns an array of tracks with a callback

function getTracks(callback, albumID){
    $.ajax({
        url:getPHPSite(),
        method:"POST",   
        data:{
            query: "SELECT idtracks FROM tracksWHERE id_album=" + albumID + ";"
        },


        success: function(response){
            array_tracks=JSON.parse(response);   
            callback(array_tracks);
        }, //...everything else

By putting breakpoints, I discovered that the first for loop is executed separately

albumID=1
albumID=2
albumID=3
...end

and only then the getTracks() is executed.

I want the getTracks() to be executed for every iteration of albums.

Why does it happen and how can I resolve this?

Upvotes: 2

Views: 84

Answers (1)

fjcero
fjcero

Reputation: 175

If you have problems with the Javascript asynchronous way, you could disable with the async: false flag http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings, but you will loose the javascript power.

One of the ways I think this could be done is create an array with all the resultant Ids of the first endpoint, and then do the foreach to that array, instead of embedding ajax inside ajax, but just for code maintainability.

Upvotes: 1

Related Questions