Q:

repeating last element in jquery and ajax

I have an issue with my 'for' loop with my ajax request. I know there are a lot of not-best-practice in here so forgive me, I'm just starting =]
So here is my code:
var ServersObject = $("tr td:nth-child(2)");
var ServerArray = $.makeArray(ServersObject);
console.log(CurrentServer + 'outside ajax');
for (var i = 0; i < ServerArray.length; i++) {
    var CurrentServer = ServerArray[i].outerText;

    $.ajax({
        type: 'GET',
        data: { 'Server': CurrentServer },
        url: 'http://localhost/check',
        success: function(data) {
            if (data == '200') {
                console.log(CurrentServer + 'inside ajax');
                $("td:contains('" + CurrentServer + "')").next().text("OK");
            } else {
                $("td:contains('" + CurrentServer + "')").next().text("Not OK");
            }
        }
    });
}

As you can see I have two 'Console.log' messages, and an array of servers. the "outside ajax" message is showing all of the servers one by one like it should, but the "inside ajax" one shows only the last server in the array..
What am I doing wrong?
Thanks!

A:

You need to use a closure to fix the value in the callback, since CurrentServer changes as you iterate over the array. There are several ways to do this. Here is one:
for (var i = 0; i < ServerArray.length; i++) {
    var CurrentServer = ServerArray[i].outerText;

    (function(cs) {
      $.ajax({
        type: 'GET',
        data: { 'Server': cs },
        url: 'http://localhost/check',
        success: function(data) {
            if (data == '200') {
                console.log(cs + 'inside ajax');
                $("td:contains('" + cs + "')").next().text("OK");
            } else {
                $("td:contains('" + cs + "')").next().text("Not OK");
            }
        }
      });
    })(CurrentServer);
}

The idea is that the value you pass to a function (for scalar objects like strings) doesn't change outside of the function. So by passing the value into a function (closure) in this way, you 'fix' the value that is referenced by the code in the success callback.

