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.
Add a scoping function (an IIFE) that creates a new scope for your variable:
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.