I created a for loop and runs Javascript(jquery)code in it. But somehow the for loop variable increments automatically.
for (var i=0; i<len; i++) { //len=2
console.log(i); // outputs 0 and 1 as expected
$.ajax({
url:'execute.php',
method:'GET',
data:{
link: items[i]
},
success:function(data){
console.log(i); //outputs 2 and 2. It sould be 0 and 1
$("#div1").html(data);
var item = $(".sticky-item-title .title").html();
$("#product-"+ i).html(item);
},
error:function(data){
alert('error' + data);
}
});
}
The console.log before $.ajax shows 0 and 1 as expected (I have 2 items in len). But the console.log inside success function shows as 2 and 2. Why and where is it incremented. I tried this code
for (var i=0; i<len; i++) {
var s=i;
$.ajax({
url:'execute.php',
method:'GET',
data:{
link: items[s]
},
success:function(data){
console.log(s); //outputs 1 and 1. It should be 0 and 1
$("#div1").html(data);
var item = $(".sticky-item-title .title").html();
$("#product-"+ s).html(item);
},
error:function(data){
alert('error' + data);
}
});
}
Here the variable s show 1 and 1 instead of 0 and 1.
What am I doing wrong here. Thanks in advance