0

I have this script which pings 4 servers. It contains of a loop which sends 4 requests and sets callbacks.

var servers = new Array(
    {
        css: 'vanilla',
        ip: 'play.example.com',
        port: '25565'
    },
    {
        css: 'uhc',
        ip: 'uhc.example.com',
        port: '25565'
    },
    {
        css: 'ftb',
        ip: 'ftb.example.com',
        port: '25565'
    },
    {
        css: 'ts',
        ip: 'ts.example.com',
        port: '8765'
    }
);

for(var i = 0; i < servers.length; i++) {

    $.get('status.php', { 

        ip: servers[i]['ip'], 
        port: servers[i]['port'] 

    }, function(data) {

        var server = servers[i];

        data = $.parseJSON(data);

        if(data.status == 'online') {

            $('.'+server.css+' .status').addClass('online').text('Online');

        } else {

            $('.'+server.css+' .status').addClass('offline').text('Offline');
            $('.'+server.css+' .text-field').attr('disabled', true);

        }
    });

My problem is that when the callback is fired, the servervariable have already changed, and so have the i from the loop. How can I parse the index to the callback function?

Jonas Røssum
  • 355
  • 2
  • 9
  • 2
    Duplicate: http://stackoverflow.com/questions/1451009/javascript-infamous-loop-problem. An easy way to solve it since you're on jQuery is to just use `$.each` which already creates a new closure for you. – elclanrs Aug 05 '13 at 02:09

1 Answers1

1

Best way is to pass the value in as a param to status.php and return it to the callback. Thats the only reliable way to know who the callback is for.

Khary
  • 140
  • 1
  • 1
  • 8