Search code examples
javascriptjsonpjquery-callback

How to get whole data out of callback function in javascript


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


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