Skip to content Skip to sidebar Skip to footer

For Loop Returns Same Value Repeatedly In Ajax Call

I'm trying to use a for loop to cycle through an array of URLs and use them for ajax calls. Outside of the ajax call, i changes value correctly, but when I try and access it from i

Solution 1:

You only have one variable i. When the callbacks fire, it has its final value of 2.

Make a closure.

Solution 2:

The call back function is called AFTER the AJAX call completes. To prevent this, try setting async to false

var i = 0;

for(i = 0; i <= 1; ++i) {

console.log("Value outside of call = " + i);

var currentIndex = i;

$.ajax({ url : urls[currentIndex], dataType : 'jsonp', timeout : 3000, count : 0, async : false, success : function(data) {

console.log("Value inside of call = " + currentIndex);

shotInfo[currentIndex] = data;

},

error : function() {

}
    })
}

Solution 3:

Basically, the success call back happens after the AJAX request completes. That may be the issue. Try if this works.

var i = 0;
for(i = 0; i <= 1; ++i) {
    console.log("Value outside of call = " + i);
    var currentIndex = i;
    $.ajax({
        url : urls[currentIndex],
        dataType : 'jsonp',
        timeout : 3000,
        count : 0,
        success : function(data) {
            console.log("Value inside of call = " + currentIndex);
            shotInfo[currentIndex] = data;
        },
        error : function() {
        }
    })
}

Post a Comment for "For Loop Returns Same Value Repeatedly In Ajax Call"