0

Possible Duplicate:
Javascript infamous Loop problem?

I am having troubles trying to access a variable inside a $.post function.

The value of the variable a inside the function is always the same: 7. But outside it, it increases as I want.

Why is this happening? How can I do a loop for a $.post function?

for(var a=0; a<7; a++){
    console.log(a); /* increasing value */

    $.post("http://"+ document.domain + "/posts/user/xxxxx",
        function(departments){
        console.log(a);  /*value of 7*/

    });
}

Thanks.

Community
  • 1
  • 1
Alvaro
  • 40,778
  • 30
  • 164
  • 336
  • 4
    ref: [Javascript infamous Loop problem?](http://stackoverflow.com/questions/1451009/javascript-infamous-loop-problem) (there should be a *close* option, just for this ever recurring question, no offence!) – Yoshi Dec 04 '12 at 15:09
  • 1
    Oh yea, just make 7 Ajax requests in a row. Your server will be fine. `:P` – Šime Vidas Dec 04 '12 at 15:11
  • @Sime, is the only way as far as I know to obtain 7 arrays of different data from the DB... – Alvaro Dec 04 '12 at 15:14
  • @Steve Wait, why not make the server script get all the data from the DB, and then return it in one response. Yes, I'm a genius! `:P` – Šime Vidas Dec 04 '12 at 15:17
  • @Steve: I don't see any difference between the seven requests, did you forgot to send `a`? Anyway, you might restructure your API so it could return the 7 arrays in one single request – Bergi Dec 04 '12 at 15:17
  • @Bergi, I just didn't publish all the code so I reduced it and of course, the URL call has no sense now :) – Alvaro Dec 04 '12 at 15:21

1 Answers1

3

Either give each for iteration it's own scope, or use $.ajax and the context option.

for(var a=0; a<7; a++){
    (function(a){
        console.log(a); /* increasing value */

        $.post("http://"+ document.domain + "/posts/user/xxxxx",
            function(departments){
            console.log(a);  /*value of 7*/

        });
    })(a);
}

with $.ajax...

for(var a=0; a<7; a++){
    console.log(a); /* increasing value */

    $.ajax({
        url: "http://"+ document.domain + "/posts/user/xxxxx",
        type: "POST",
        context: a,
        success: function(departments){
            console.log(this);  /*value of 7*/    
        }
    });
}
Kevin B
  • 94,570
  • 16
  • 163
  • 180