0

i need to get 4 request from the server, i have stored all this 4 urls in this way. for information this is raw url (http://www.earthtools.org/timezone/40.714352/-74.0059731);

var nationZone = {
    getNewYorkLocalTime :  'getTime.php?lat=40.7143528&lan=-74.0059731',
    getLondonLocalTime : 'getTime.php?lat=51.5001524&lan=-0.1262362',
    getChennaiLocalTime :  'getTime.php?lat=13.060422&lan=80.249583',
    getBangaloreLocalTime:'getTime.php?lat=12.9715987&lan=77.5945627'

}

this is calling my getTime.php and retrieving the result.

for that, i created this for in loop, but this prints only one time intead of 4 times? how can i make this to call 4 request ?

for(zone in nationZone ){
    if (window.XMLHttpRequest){
        zone=new XMLHttpRequest();
    }else{
        zone=new ActiveXObject("Microsoft.XMLHTTP");
    }
    zone.onreadystatechange=function() {
        if(zone.readyState==4 && zone.status==200){
            alert(zone.responseText);
        }
    }
    zone.open("GET",nationZone[zone],true);
    zone.send();
}

I do not mind using a solution that involves an additional third party library

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
3gwebtrain
  • 14,640
  • 25
  • 121
  • 247
  • 1
    possible duplicate of [Access outside variable in loop from Javascript closure](http://stackoverflow.com/questions/1331769/access-outside-variable-in-loop-from-javascript-closure) – Felix Kling Nov 17 '11 at 10:12

3 Answers3

1

You are using the same name for the loop variable and the XHR. Don't do that.

EDIT: Also, this question has the jQuery tag, but you are not using jQuery. Instead of doing your own XHR stuff, use jQuery's ajax implementation through $.ajax or $.get. Also consider using JSONP, if the remote server supports it.

Anders Marzi Tornblad
  • 18,896
  • 9
  • 51
  • 66
1

You can try this if your using jQuery, but I doubt about it to work, because cross domain ajax is not allowed.

var nationZone = {
    getNewYorkLocalTime :  'getTime.php?lat=40.7143528&lan=-74.0059731',
    getLondonLocalTime : 'getTime.php?lat=51.5001524&lan=-0.1262362',
    getChennaiLocalTime :  'getTime.php?lat=13.060422&lan=80.249583',
    getBangaloreLocalTime:'getTime.php?lat=12.9715987&lan=77.5945627'

}

$.each(nationZone , function(key, value){
    $.get(value, function(response){
        alert(response);
    });
});
Niels
  • 48,601
  • 4
  • 62
  • 81
0

zone variable inside the if/else block is overwriting the zone from the for loop. Hence your loop only has one zone object to handle by the time it finishes the first iteration.

Use some other var name inside the function. The line :

`zone.open("GET",nationZone[zone],true);`

should say

`newZoneVariable.open("GET", nationZone[zone], true);`

where newZoneVariable is the var used inside the loop body.

Arindam
  • 998
  • 1
  • 8
  • 20