views:

118

answers:

1

Hello all,
I'm trying to use youtube's api to bring back a listing of a user's videos. The request url looks something like:
http://gdata.youtube.com/feeds/api/users/username/uploads
with 'username' being the correct username. This bring back the appropriate url in the browser. However when I try to access that url via jQuery's $.ajax or $.get functions, using something like:

$.ajax({   

    //set parameters
    url: "http://gdata.youtube.com/feeds/api/users/username/uploads",
    type: "GET",

    //on success
    success: function (data) {
      alert("xml successfully captured\n\n" + data);
    },
    //on error
    error:function (XMLHttpRequest, textStatus, errorThrown, data){
      alert(" We're sorry, there seem to be a problem with our connection to youtube.\nYou can access all our videos here: http://www.youtube.com/user/username");
      alert(data);
    }      
  });

  $.get("http://gdata.youtube.com/feeds/api/users/username/uploads", function(data){
    alert("Data Loaded: " + data);
  });

I get an empty document returned. Any ideas why this is?

+2  A: 

You're hitting the same-origin policy here, preventing cross-domain requests...but you can do what you're after with JSONP in this case (since youtube supports it, as long as JSON data is an option in your code, usually this is preferred so I'm hoping this is a solution for you). Using JSONP looks like this:

$.ajax({
    url: 'http://gdata.youtube.com/feeds/api/users/username/uploads?alt=json​',
    dataType: 'jsonp'​​​​,
    success: function(data) {
        console.log(data); //entire object here
        //another example
        alert("Feed title: " + data.feed.title.$t);
    }
});​

You can see a working demo here, this grabs the video upload feed for nike. Just explore the object in the console to see what data you want and grab it :)

Nick Craver
Thanks so much! however, I get an "unexpected token: ILLEGAL" error after the line with "datatype:'jsonp'"...
danwoods
Even when I directly copy the example code...
danwoods
Never mind. Some invisible characters lurking in the code :) Thanks again, I appreciate it...
danwoods