0

I have a function that is pulling in data with an AJAX call. I am creating an object that I would like to access in other functions. So I would like to send the data into another global object.

Here is the currently javascript:

var foursquareMapData = [];

function MapData() {

    $.ajax({
        dataType: 'jsonp',
        url: 'https://s3.amazonaws.com/sxsw_trending/sxsw_trending.json',
        jsonp: "callback",
        jsonpCallback: "sxswTrending",
        success: function (data) {
            //console.log(data);
            // var foursquareMapData = [];
            for (var i = 0; i < data.Trending.length; i++) {

                var mapData = {
                    index: i + 1,
                    lat: data.Trending[i].lat,
                    lng: data.Trending[i].lng,
                    count: data.Trending[i].hereNow,
                    address: data.Trending[i].address
                }
                //console.log(mapData);
                foursquareMapData.push(mapData);
            }
            //console.log(foursquareMapData);
        }
    });

}
console.log(foursquareMapData);

Pushing the 'mapData' object into the foursqureMaData doesn't seem to working. I might not be doing this properly?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Xtian
  • 3,535
  • 11
  • 55
  • 91
  • Hopefully this helps you to understand how Ajax works: http://stackoverflow.com/q/14220321/218196. (though in your case, you are actually not using Ajax, but the outcome is the same) – Felix Kling Feb 17 '13 at 19:07
  • That is a great response. Thank you – Xtian Feb 18 '13 at 18:28

1 Answers1

0

That's because you call the console log before the ajax call finished. Try to output it at the end of your ajax success function, then it should be correct.

[edit]
oh just saw you already have a console.log at the end of the success function. didn't that show the correct data?

[edit2]
you do call MapData() somewhere, right? Because it's not in your code.

Andy
  • 29,707
  • 9
  • 41
  • 58
  • yes, i call the function in side of $(document).ready(function(){ – Xtian Feb 17 '13 at 19:12
  • @Xtian well, i just copied your exact code into jsFiddle and it works as expected: http://jsfiddle.net/C6TKV/ – Andy Feb 18 '13 at 08:06