I use the ajax-request queue as posted here: Wait until all jQuery Ajax requests are done?
Now i wrote the following code to implement it:
for (var i=0; i<3; i++) {
$.ajaxQueue({
url: '/action/',
data: {action:'previous',item:i*-1},
type: 'GET',
success: function(data) {
$('.item-history .itemlist').prepend(data['item_add']);
$('.item-history .itemlist:first .index').html(data['newitemindex']);
//alert(data['newitemindex'])
};
});
As long as i use the alert to proof the response from the server, everything works fine. But as soon as i run the code, as shown, without the alert, data[‘newitemindex’] behaves as it was a global variable – it always returns the value of the last item.
I tried to set up a jsfiddle on this, but as i have never used that site, i could not get the ajax to work. If somebody wants to have a look at it anyway: http://jsfiddle.net/marue/UfH5M/26/
Your code is setting up three ajax calls, and then applying the result of each of them to the same elements (there’s no difference in the selectors you use inside your
successfunction). For the$('.item-history .itemlist')elements, you should see the result of each call prepended to the elements because you’re usingprepend(), but for the$('.item-history .itemlist:first .index')elements, you’re usinghtml()which replaces the elements’ contents, and so for those you’ll see the result of the last call that completes.Off-topic: To fix that, you’re probably going to want to use your loop variable in some way in the
successfunction. That could lead you to a common mistake, so here’s an example of the mistake and how to avoid it.Let’s say I have these divs:
And I want to use three ajax calls to populate them when I click a button, using a loop counter from
1to3. I might think I could do it like this:Live example (which fails)
But (as indicated) that doesn’t work. It doesn’t work because each
successfunction we create has an enduring reference to theivariable, not a copy of its value as of when thesuccessfunction was created. And so all threesuccessfunctions see the same value fori, which is the value when the function is run — long after the loop is complete. And so (in this example), they all see the value4(the value ofiafter the loop finishes). This is how closures work (see: Closures are not complicated).To fix this, you set it up so the
successfunction closes over something that isn’t going to be updated by the loop. The easiest way is to pass the loop counter into another function as an argument, and then have thesuccessfunction close over that argument instead, since the argument is a copy of the loop counter and won’t be updated:Live example