27

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.

simonwjackson
  • 1,818
  • 4
  • 25
  • 33

2 Answers2

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

That should do it.

Old docs

2021 docs

Rojo
  • 2,749
  • 1
  • 13
  • 34
jarcoal
  • 1,445
  • 2
  • 16
  • 19
  • 4
    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." – Derek Swingley Nov 19 '09 at 07:12
  • 2
    this works but also gives this warning in my Chrome browser: ```pace.min.js:2 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.```. Apparently this is because of setting `async: false`. Any ideas of an alternative that would remove this warning? – tsando Jan 22 '18 at 13:06
2

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
  • 65,509
  • 13
  • 109
  • 118