Sam
Sam

Reputation: 7058

Arrays disappear outside of JSON request

I am attempting to set up an array with the various properties of a YouTube video (you may be thinking this is somewhat superfluous, however I am planning on adding other sources in the future). I am able to add these values into the array within the JSON request, but once I get out of it, they just disappear. Any ideas?

var socialPosts = new Array(); 
$.getJSON('https://gdata.youtube.com/feeds/api/videos?author=google&max-results=5&v=2&alt=jsonc&orderby=published', function(data) {
    for(var i=0; i<data.data.items.length; i++) { //for each YouTube video in the request
        socialPosts[i]={date:Date.parse(data.data.items[i].uploaded), title:data.data.items[i].title,source:"YouTube", thumbnail:data.data.items[i].thumbnail.hqDefault, url:'http://www.youtube.com/watch?v=' + data.data.items[i].id}; //Add values of YouTube video to array
    }
    console.log(socialPosts[0].date); //This returns the correct data
});
console.log(socialPosts[0].date); //This returns with undefined

Upvotes: 0

Views: 194

Answers (2)

Patrick Evans
Patrick Evans

Reputation: 42736

Because that is an Ajax function and it happens async meaning the code outside the closure executes before the call is finished

Upvotes: 0

Adil
Adil

Reputation: 148150

You are trying to access results of Ajax asyn call which are not yet returned. You need to use result in call back function or pass the results to some function.

var socialPosts = new Array(); 
$.getJSON('https://gdata.youtube.com/feeds/api/videos?author=google&max-results=5&v=2&alt=jsonc&orderby=published', function(data) {
    for(var i=0; i<data.data.items.length; i++) { //for each YouTube video in the request
        socialPosts[i]={date:Date.parse(data.data.items[i].uploaded), title:data.data.items[i].title,source:"YouTube", thumbnail:data.data.items[i].thumbnail.hqDefault, url:'http://www.youtube.com/watch?v=' + data.data.items[i].id}; //Add values of YouTube video to array
    }
    console.log(socialPosts[0].date); //This returns the correct data
    somefun(socialPosts[0].date); 
});

Upvotes: 2

Related Questions