views:

228

answers:

1

Part of a website I am working on is a video page. I am pulling the videos from a YouTube account by accessing the YouTube Data API. Grabbing the videos in no particular order and not sorted works fine, but when I try to sort them into categories, I start running into trouble. Let's say there are three categories, Fruit, Vegetable, Pets. Instead of grabbing all the videos at once, I want to grab all the videos tagged with Fruit, append them to a <ul id="Fruit">. Then request all videos tagged with Vegetable, etc.

When starting out, I had the browser alert when it had finished getting the request and then appending the appropriate list. After I took out the alert, it still worked, but not the way I expected. Either the loop is advancing too quickly, or not advancing at all, but I can't seem to spot the mistake. What ends up happening is that all the videos get put into one list, <ul id="Vegetable">.

Please note: I am using a plugin called jGFeed which wraps the jQuery getJSON function, so I believe you can treat it as such.

 var videoCategories = ['Fruit', 'Vegetable', 'Pets'];

 for (var i = 0; i < videoCategories.length; i++) {
    var thisCategory = videoCategories[i];
    $.jGFeed('http://gdata.youtube.com/feeds/api/users/username/uploads?category='+thisCategory,
    //Do something with the returned data
    function(feeds) {
       // Check for errors
       if(!feeds) {
         return false;
       } else {
         for(var j=0; j < feeds.entries.length(); j++) {
            var entry = feeds.entries[i];
            var videoUrl = entry.link;
            $('ul#'+thisCategory).append('<li><a href="#" id="'+videoUrl+'">'+entry.title+'</a></li>');
         }
       });
 }
+2  A: 

The problem is, you're using the 'thisCategory'-variable to set the category-name. The problem is, the value if this variable changes, while you're waiting for a response from the server.

You could try to put the whole script inside a function:

var videoCategories = ['Fruit', 'Vegetable', 'Pets'];

for (var i = 0; i < videoCategories.length; i++) {
    getCategory(videoCategories[i]);
}

function getCategory(thisCategory)
{

    $.jGFeed('http://gdata.youtube.com/feeds/api/users/username/uploads?category='+thisCategory,
    //Do something with the returned data
    function(feeds) {
       // Check for errors
       if(!feeds) {
         return false;
       } else {
         for(var j=0; j < feeds.entries.length(); j++) {
            var entry = feeds.entries[i];
            var videoUrl = entry.link;
            $('ul#'+thisCategory).append('<li><a href="#" id="'+videoUrl+'">'+entry.title+'</a></li>');
         }
       });
 }

I haven't tested this, so I'm not sure if it works..

Pbirkoff