views:

355

answers:

2

The folowing script does not wait for $.get to finish loading the page before continuing with the loop:

$.each(data.songs, function(index, val) {
    $('#nowartist')
         .append('song starting');
    $.get("http://localhost/play.php", function(data){
         alert('done');
    });
});

data is a JSON object

Any ideas or comments will be greatly appreciated.

+7  A: 
$.ajax({
     async: false,
     type: 'GET',
     url: 'http://localhost/play.php',
     success: function(data) {
          //callback
     }
});

That should do it.

http://docs.jquery.com/Ajax/jQuery.ajax#options

jarcoal
Just so the OP is aware, from the link above: "Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active."
Swingley
A: 

If you didn't want to potentially lock the browser, you could do it this way which just keeps chugging through songs until they are all processed.

function play_next(){
   var song = data.songs.shift(); // Removes the first song and stores it in song

   $('#nowartist').append('song starting');

   $.get("http://localhost/play.php", function(ret_data){
      alert('done');
      if(data.songs.length) play_next(); // Call next song if more songs exist;
   });
}
play_next(); // Start it off

Note, it does alter the data.songs array by removing items upon processing. If this is a problem, duplicate the array before starting so it removes elements from the duplicate array.

On a side note, I am assuming you didn't paste all your code... right now it loads the same page for every song, but nothing from the song item is being used to alter the request in any way.

Doug Neiner