Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through an array while performing a request for each entry

Here is my issue. I have an array containing the name of cities that I need to lookup the weather for. So I'm looping through each city and performing an AJAX request to retrieve the weather.

var LOCATION = 'http://www.google.com/ig/api?weather=';

$( document ).ready( function() {
    for( var cityIdx = 0; cityIdx < cities.length; cityIdx++ ) {
        $.ajax({
            type: 'GET',
            url: LOCATION + cities[ cityIdx ],
            dataType: 'xml',
            success: function( xml ) {
                if( $( xml ).find( 'problem_cause' ) != 0 ) {
                    // Do what I want with the data returned
                    var weather = $( xml ).find( 'temp_c' ).attr( 'data' );
                }
            }
        });
    }
});

The issue I'm encountering is that in the success function, I can't access the city name (via cities[cityIdx]). I inserted an alert() in the for loop and the success function and it seems like the loop gets executed cities.length times, then I get the success function alerts. My goal is to simply loop through each city getting the weather and showing it on my page along with the associated city name.

Also, what would you suggest I should do to separate content with presentation?

Thank you. :)

like image 561
Mike Avatar asked Dec 08 '22 08:12

Mike


1 Answers

I suspect that your problem is similar to the example at http://ejohn.org/apps/learn/. The index variable cityIdx is updated in the closure you create as the for loop is processed, so by the time your function on success is run cityIdx will point to the last element in the array. The solution is to use an evaluated anonymous function to create an independent context, where the index value doesn't get updated.

//...
success: (function(cities, idx) {
    return function( xml ) {
      if( $( xml ).find( 'problem_cause' ) != 0 ) {
        // Do what I want with the data returned
        // use cities[idx]
        var weather = $( xml ).find( 'temp_c' ).attr( 'data' );
      }
    };
  })(cities, cityIdx)
//...
like image 96
bandi Avatar answered May 20 '23 20:05

bandi