Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Possible to wait for $.get to finish loading before continuing?

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.

like image 782
simonwjackson Avatar asked Nov 19 '09 07:11

simonwjackson


2 Answers

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

That should do it.

Old docs

2021 docs

like image 60
jarcoal Avatar answered Sep 23 '22 19:09

jarcoal


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.

like image 29
Doug Neiner Avatar answered Sep 19 '22 19:09

Doug Neiner