olivierGrech olivierGrech - 7 months ago 6
Javascript Question

Index not taking the right value within an $http.post query

I'm doing a loop like this :

for (var index in data)
{
console.log(index);
$http.post('server.php')
.success(function(data, status)
{
console.log(index);
}
}


The first
console.log()
displays :
0,1,2,3,4,5


The second
console.log()
displays :
5,5,5,5,5,5


And I have really no idea why. Is it because of the fact that i'm using 2 variables named
data
? I tried renaming one, but it didn't fixed the issue.

Answer

You need to use Closures in this aspect. The closure, "packs" the value of the index, while it gets executed at a callback, later.

for (var index in data) {
  (function(index) {
    $http.post('server.php')
    .success(function(data, status) {
      console.log(index);
    });
  })(index);
}
Comments