-1

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

1

3 Answers 3

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);
    });
});
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

While this is true, this is not the only problem and changing the name won't solve it.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.