I have an each() function that iterates across a number of tr elements, in reverse (lol).
<table>
<tr><th>header row</th></tr>
<tr><td id="row1">row 1</td></tr>
<tr><td id="row2">row 2</td></tr>
<tr><td id="row3">row 3</td></tr>
</table>
$($("table tr:gt(0)").get().reverse()).each(function() {
tr=$(this);
console.log(tr); // correctly prints my TRs in reverse order
}
Works great, but now watch:
$($("table tr:gt(0)").get().reverse()).each(function() {
tr=$(this);
console.log(tr); // correctly prints my TRs in reverse order
$.ajax({
type: "POST",
url: "ajax.php",
data: data,
dataType: "json",
success: function(json) {
console.log(tr); // incorrectly prints TRs in not-reverse order
// TRs are not matched with above. Chaos ensues.
}
});
});
I figure what’s happening is the Ajax call is taking longer to execute than the iteration over than the TR elements… I suppose I could set async to false, but is there a way to keep this asynchronous?
SOLUTION
As @Nicola pointed out below, it’s probably best to just send the ID to the server along with the Ajax call and retrieve it again in the success function.
This is because you are firing one ajax call for every
<tr>and since calls are asynchronous, you have no guarantee that they will return in order, that means that the second call is fired just after the first call is fired, withouth waiting for a response. Settingasynctofalsesolve the problem, if you want to keep things “async” you should fire the second call in the success callback, but your iteration won’t wait, so you need to refactor everything