0

I have the following code, which has been simplified for this question. Basically i have a loop, that, on each iteration, calls the jquery getJSON function, calling out to a API end point to grab some weather data. The problem is that i need to access the index from the loop, when the getJSON request was fired, and am having some troubles with it. I need to know what index the request was for, so i can match it with some data from a database.

The code:

function buildCities()
{    
    for (var i = 0; i < 7; i++) 
    {
        var jqxhr = $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=usa,phoenix&units=metric", function(response) 
       {
           alert(i); //this will always be 7 - this is the issue.  i desire it to be 0,1,2,3, etc.... 
       });
    }
}

Here is a JSFiddle that shows the issue, and that you can work on if need be ;) - http://jsfiddle.net/5tr34k/0xshvrzp/

The request: How can i inject or otherwise access this index (i) inside of the callback function for the request ? Thanks for any help.

2 Answers 2

4

Add a scoping function (an IIFE) that creates a new scope for your variable:

function buildCities()
{    
    for (var i = 0; i < 7; i++) 
    {
        (function(index){
            var jqxhr = $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=usa,phoenix&units=metric", function(response) 
           {
                alert(index); 
           });
        })(i);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

wickedy! this works pretty good. now i just need the stupid API to respond better to quick calls!
@jordan.peoples: Yes "Types" are available in "Stereo", but not recommended :)
0

Also if you have access to ES6 changing i to val instead of var will also work.

Main issue is you are dealing with function scoping so you keep reusing the same variable vs val which is {} scoped, or TrueBlueAussie answer which creates a new scope for you.

3 Comments

Are your seriously suggesting an upcoming standard as a solution for a current real-world problem? :)
Ecmascript 6 is the newest version of javascript standard , @TrueBlueAussie you already had a good answer while I was writing mine so was just thinking of another way to add value instead of rewriting yours with different flavor lol.
Come back in a couple of years and your answer will, one day, be the preferred solution :)

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.