3
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?

2

1 Answer 1

5

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:

Sign up to request clarification or add additional context in comments.

8 Comments

Besides !, + - ~ would do the same job
@Sirko - can you explain more? what is ! for?
if your code works it is a perfect code. How is my code? longer but I think true.
@imsiso You have to tell the parse somehow, that this is a function expression and not a declaration (see, e.g., this question). In my answer I used a ! to do so. In general there are plenty of ways to do this.
@Sirko - would ! be same as using var tmp=functio...? and why i is still known in the ajax callback?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.