Reputation: 1
I'm totally new to jquery but I have a .each loop that fetches some data using ajax and then updates list elements. Right now the .each loop does all list elements at the same time... I need it to do the first one, wait till its done then do the second one etc. etc. I do NOT want to use delay. I want the loop to actually wait until the data is fetched then move on to the next element. Please no faking it using delay. Here is my code simplified.
$(document).ready(function() {
$.ajaxSetup({cache:false});
$('#friendslist li').each(function(index) {
var post_id = $(this).attr("id")
$(this).find(".status div").html("<img src='http://www.url.com/image.jpg'/>");
$(this).find("#replace").load("http://www.url.com/ajaxstuff",{id:post_id});
})
});
Thanks in advance for the help!
Upvotes: 0
Views: 538
Reputation: 29658
Set up a queue where you place each of your functions. Call the first function in the queue. When it finishes executing, it should pop the next function off of the queue and execute it, and so on. Do not use synchronous Ajax requests, since this will lock up the browser.
Simplified example:
var queue = [];
queue.push(function(){
$("#replace").load("somefile.html", function(){
// Still need to check that another element to pop exists
(queue.pop())();
});
});
queue.push(function(){
$("#replace2").load("somefile2.html", function(){
// Still need to check that another element to pop exists
(queue.pop())();
});
});
(queue.pop())();
Please note that this can be further optimized, and you still need to check that another exists that you can pop and execute. But, it's a start.
Upvotes: 2
Reputation: 40863
Instead of doing an $.each loop, you could simply recursievely call the function again in the load()
handler.
function LoadFriends(i) {
$("#friendslist li:eq(" + i + ")").load('/echo/html/', {
html: 'Hello!', delay: 1
}, function() {
LoadFriends(i+1);
});
}
LoadFriends(0);
Code Example on jsfiddle.
Putting that with your sample code:
$(document).ready(function() {
$.ajaxSetup({cache:false});
function LoadFriends(i) {
var $li = $("#friendslist li:eq(" + i + ")");
var post_id = $li.attr("id")
$li.find(".status div").html("<img src='http://www.url.com/image.jpg'/>");
$li.find("#replace").load("http://www.url.com/ajaxstuff",{id:post_id}, ,
function(){
LoadFriends(i+1);
});
}
LoadFriends(0);
});
Upvotes: 0
Reputation: 30636
You'll need to restructure you code. You to run the next "query" in the callback of the prior query. Since .load will run asynchronously.
Upvotes: 0
Reputation: 62392
You can set the async
option to false
if you want the loop to wait on it, which will render the browser un-usable while it is executing.
like this
$.ajaxSetup({cache:false, async:false});
Upvotes: 2