views:

56

answers:

2
+1  Q: 

$.getJSON problem

Hi, I am creating an object for handling youtube api.
In my object I have to methods :

  • getCommentList - getting a url for the current upload,for example http://gdata.youtube.com/feeds/api/videos/VIDEO_ID/comments?alt=json and return an array of objects - author of the comment and the content of the comment.
  • getEntriesObject - returning an array with objects for each upload entry we have title,thumbnail,and the comment list that returned from getCommentList

The Code Is here - http://pastebin.com/hipTM5Zi The Problem I am getting that - first I have console.log(currentObject) - I am getting the title,the thumbnail url and the comments I am not getting.
The second problem is that I am running getEntriesObject and I am getting an empty array.


Thanks,Yosy
By the way,I am using jQuery

+1  A: 

When you call return in the callback to $.getJSON you are returning only that callback function, not the "outer" getCommentObject. Thus when you later call that.getCommentObject you're not getting anything in return (undefined).

getCommentObject: function(url){
   if( url ){

      // Snip ...

      $.getJSON(url,function(data){

         // Snip ...

         return commentsList; // <- Here
      });

   }
}

To amend this make getCommentObject take a callback function.

getCommentObject: function(url, callback){
   if( url ){

      // Snip ...

      $.getJSON(url,function(data){

         // Snip

         // Remove the return statement
         callback(commentsList);
      });

   }
}

Call this function like this:

that.getCommentObject(
    currentEntry.gd$comments.gd$feedLink.href + "?alt=json", 
    function (commentsList) { 
       currentObject['comments'] = commentsList; 
});

Replacing

currentObject['comments'] = that.getCommentObject(currentEntry.gd$comments.gd$feedLink.href + "?alt=json");
adamse
Thanks You,It works fine :)
Yosy
@Yosy: If an answer is correct please use the green checkmark to indicate it!
adamse
+1  A: 

You are getting the empty comments because the return statement is in the wrong place. It is in the getJSON callback function. You need to move it from line no 19 to 21 so that it becomes the return statement for getCommentObject. This will fix the first problem. (comments undefined)

Second getEntriesObject is empty because, for some users youtube is returning "Service Unavailable" error for the json request. This happened for when I tried with some random username on youtube.

I checked your program with youtube username "google". After changing the return statement it worked fine.

Hope this helps.

Uttam