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?

Chan
  • 1,597
  • 1
  • 19
  • 33
  • Here is [answer][1] to your question - use factory function. [1]: http://stackoverflow.com/questions/10171106/how-to-pass-an-element-to-jquery-post-inside-a-loop – yAnTar Oct 31 '13 at 08:47
  • [How do JavaScript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Andreas Oct 31 '13 at 08:55

1 Answers1

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:

Community
  • 1
  • 1
Sirko
  • 65,767
  • 19
  • 135
  • 167
  • Besides `!`, `+` `-` `~` would do the same job – lastr2d2 Oct 31 '13 at 08:53
  • @Sirko - can you explain more? what is `!` for? – ncm Oct 31 '13 at 08:54
  • if your code works it is a perfect code. How is my code? longer but I think true. – ncm Oct 31 '13 at 08:57
  • @imsiso You have to tell the parse somehow, that this is a function expression and not a declaration (see, e.g., [this question](http://stackoverflow.com/q/1013385/1169798)). In my answer I used a `!` to do so. In general there are plenty of ways to do this. – Sirko Oct 31 '13 at 08:57
  • @Sirko - would `!` be same as using `var tmp=functio...`? and why i is still known in the ajax callback? – ncm Oct 31 '13 at 09:02
  • @imsiso As for the first question, yes, if you then call `tmp` in each loop. As for the second question: By using a function, the value is copied (as all primitives will be in JS) and hence inside the function the copied value will be used. Furthermore, you could look at [this question](http://stackoverflow.com/q/111102/1169798) to see, why the callback sees the version of `i` created by the IIFE. – Sirko Oct 31 '13 at 09:08
  • if `!function(i) {}(i);` equal to `(function(i) {}(i))`? – Chan Nov 01 '13 at 06:23
  • @吳承諺 In this context, it is. – Sirko Nov 01 '13 at 06:37