Search code examples
javascriptjquerycallbackgetjson

How to access index variable in a jquery getJson call ($.getJson) during a loop?


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.


Solution

  • 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);
        }
    }