2

I'm little stuck here, can anybody help?

I have a list of items and for each item I need to call ajax. After returning data I will process them, but with context of particular item. Please look in source code below. My problem is, that i always get i=5 for all my items. Any suggestions?

for (var i = 0; i < 5; i++) {
    $.ajax(myAjaxUrl)
        .done(function(myAjaxResponse) {
            doSomething(myAjaxResponse, i);
        })
        .fail(function() {
            console.log("ajax response fail");
            doSomething("", i);
        });
}

function doSomething(text, i) {
    console.log(text + " " + i);
}

Thanks a lot

areim
  • 3,371
  • 2
  • 23
  • 29
  • You will have to implement a lock of some sort. [SO: jQuery Ajax SyncLock](http://stackoverflow.com/a/2151648/1762224) – Mr. Polywhirl Oct 31 '14 at 16:29
  • Better dupe is http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – epascarello Oct 31 '14 at 16:29
  • Use `$.each(new Array(5), function(i) { /* your body */ })` instead of `for (var i = 0; i < 5; i++) { /* your body */ }`. See http://stackoverflow.com/a/26414099/947687 – dizel3d Oct 31 '14 at 16:33

0 Answers0