Question

I have written following function which takes a json data from a url.

function getWeatherDataForCities(cityArray){
  var arrAllrecords = [];
  var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
  for(var i in cityArray){

    for(var j=1; j<=2; j++){
        var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;

        $.ajax({
            url: jsonurl,
            dataType: "jsonp",
            mimeType: "textPlain",
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            success: function(data){
              arrAllrecords[j]["cityName"] = data.list[0].city.name;
              arrAllrecords[j]["weather"] = data.list[0].weather[0].description;

        } });
        toDaysTimestamp = toDaysTimestamp - (24*60*60);
    }   
  }

  return arrAllrecords;  //returning arrAllrecords
}

$(document ).ready(function() {

  var cityArray = new Array();
  cityArray[0] = "pune";
  var arrAllRecords = getWeatherDataForCities(cityArray);
  //Print All records returned by getWeatherDataForCities(cityArray);
});

I have written some comments in above code.I have called getWeatherDataForCities function which returns all records from url.I have declared getWeatherDataForCities array in function.I want to add all returned records in that array.I have tried as above but nothing is getting into array.

In console showing j and arrAllrecords are undefined.

How to get all records in array from callback function?

you response will be highly appreciated

Was it helpful?

Solution

Your getWeatherDataForCities function won't return anything because ajax operations are asynchronous. You need to use a callback for that.

Modify your function to accept a callback function:

function getWeatherDataForCities(cityArray, callback){
    var arrAllrecords = [];
    var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
    for(var i in cityArray){

       for(var j=1; j<=2; j++){
           var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;

            $.ajax({
                url: jsonurl,
                dataType: "jsonp",
                mimeType: "textPlain",
                crossDomain: true,
                contentType: "application/json; charset=utf-8",
                success: function(data){
                arrAllrecords[j]["cityName"] = data.list[0].city.name;
                arrAllrecords[j]["weather"] = data.list[0].weather[0].description;
                // call the callback here
                callback(arrAllrecords);
               } 
            });
           toDaysTimestamp = toDaysTimestamp - (24*60*60);
       }   
   }
}

And use it like this:

$(document ).ready(function() {
  var cityArray = new Array();
  cityArray[0] = "pune";
   getWeatherDataForCities(cityArray, function(arrAllrecords) {
       // Do something with your data
   });
});

OTHER TIPS

You are trying to use the empty array. When fetching the values it will always return you undefined.

var arrAllrecords = [];
arrAllrecords[2]; //undefined
arrAllrecords[2]["cityname"];  //undefined

Better you should use array of objects.

I don't know why you have used variable j. The below code works for me.

var arrAllrecords = [];

function getWeatherDataForCities(cityArray){

  var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
  for(var i in cityArray){

    var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
        $.ajax({
            url: jsonurl,
            dataType: "jsonp",
            mimeType: "textPlain",
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            success: function(data){

            arrAllrecords.push({
                "cityName" : data.list[0].city.name,
                "weather" : data.list[0].weather[0].description

            });
            if(arrAllrecords.length === cityArray.length) {
                callback(arrAllrecords);
            }
        } });
  }
}

function callback(arrAllrecords) {
    console.log(arrAllrecords);
}


        $(document).ready(function() {

            var cityArray = new Array();
            cityArray[0] = "pune";
            cityArray[1] = "mumbai";
            cityArray[2] = "delhi";
            getWeatherDataForCities(cityArray);


        }); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top