Reputation: 3869
I'm having issues with some jQuery code I have.
Using $.each I am looping through a few values and calling some php code. After this $.each loop is finished, I would like to load a div with certain content. I have tried loading the div after the $.each statement, but the load statement is still executed first, displaying the wrong value. When I put this load inside the $.each it works, although it loads after each iteration instead of at the end. Any ideas?
Here is the relevant part my code:
$.each(steps, function(n,step){
$.post("utility.php", {
utility: "getStepValue",
step: step
},
function(data) {
// offset clock
var step_value = data;
$.post("utility.php", {
utility: "offsetClock",
step_value: step_value
},
function(data){
// when load statement inserted here, it works fine
});
});
}
});
// this statement finishes before the $.each, showing the wrong value
$("#clock").load("utility.php", {
utility: "displayClock"
});
Upvotes: 0
Views: 288
Reputation: 25147
Get the number of steps
. Then, do the $("#clock").load("utility.php" ...
inside the second callback in the loop only if the current index is the same as the number of steps - 1. Something like this:
var count = steps.length;
$.each(steps, function(n,step){
$.post("utility.php", {
utility: "getStepValue",
step: step
},
function(data) {
// offset clock
var step_value = data;
$.post("utility.php", {
utility: "offsetClock",
step_value: step_value
},
function(data){
if(n == count - 1){
$("#clock").load("utility.php", {
utility: "displayClock"
});
}
});
});
}
});
Upvotes: 1