Search code examples
javascriptwordpressyoutubecoding-styledom-events

Grabbing Info from a YouTube Vid with Javascript (Code Needs Refining)


I'm working on a community video site (Wordpress backbone) that will allow users to simply submit a link and have all the info on the site. I have the main parts working (filtering video ID and planting value into Javascript functions which grab view count). I'm trying to grab the uploader of the video, but for some reason it doesn't seem to be working (works on my other site, ?). Here's a snippet of my code:

Assume video ID is '3DdQw4w9WgXcQ'

 //Here is the player (separate from JS, used PHP)
 <iframe width="802" height="480" src="http://www.youtube.com/embed/3DdQw4w9WgXcQ" frameborder="0" allowfullscreen></iframe>

 //Here is where I want the uploader to display, if the function doesn't execute correctly, it displays a common message, "Error"
 <div id="postedby">Error</div>

 <script type="text/javascript">
    function youtubeVidCallback( data )
        {
        document.writeln( '<h3><strong>' + addCommas( data.entry[ "yt$statistics" ].viewCount ) );
        $('#postedby').html( 'Posted by' + data.entry[ "author" ][ 0 ].name.$t );
        }
 </script>
 //This next part loads YouTube's feed and gets the script rolling
 <script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/3DdQw4w9WgXcQ?v=2&amp;alt=json-in-script&amp;callback=youtubeVidCallback"></script>

My goal is to enable this so that I can make subscription links back to the video author's channel and possibly load their avatar.


Solution

  • You have the right idea, but you shouldn't be encoding the url:

    <script type="text/javascript" src="https://gdata.youtube.com/feeds/api/videos/dQw4w9WgXcQ?v=2&alt=json-in-script&callback=youtubeVidCallback"></script>
    

    Fiddle:

    http://jsfiddle.net/EvbZm/