for (i = 1; i <= 6; i++) {
$.post("ajax.php", {param: i}, function (response) {
console.log(i);
});
}
How to get correct i variable in $.post
complete function, Can I pass variable to it?
for (i = 1; i <= 6; i++) {
$.post("ajax.php", {param: i}, function (response) {
console.log(i);
});
}
How to get correct i variable in $.post
complete function, Can I pass variable to it?
Add an IIFE to it, this will copy the outer i
for each instance:
for (i = 1; i <= 6; i++) {
!function( i ){
$.post("ajax.php", {param: i}, function (response) {
console.log(i);
});
}( i );
}
Edit
As for the question in the comments:
In the above code I use the !
to tell the parser, that there is a function expression to follow and not a function declaration. This is needed in order to have a IIFE, but you can use a whole lot of different ways to do so as mentioned by @Wayne.
For more details, have a look at this question: