Loading...
X

Facebook Like, YouTube Video Feed and AJAX using jQuery

Initially thought of just to write a small article on Facebook XFBML Like Widget but when I started writing with the demo part then realize that other things also needs explanation so now divided into 3 parts and would try to explain them individually.

This article is going to cover following topics with the final demo in the last with all the integration in ones.

  • Facebook XFBML Like Widget
  • YouTube JavaScript API
  • jQuery AJAX

One of the problems comes when you try to make dynamic facebook like button to show the count based upon the particular URL and parse it.

Facebook Like Widget:

The Like button lets a user share your content with friends on Facebook. When the user clicks the Like button on your site, a story appears in the user’s friends’ News Feed with a link back to your website

There are two Like button implementations: XFBML and Iframe. The XFBML version is more versatile, but requires use of the JavaScript SDK. The XFBML dynamically re-sizes its height according to whether there are profile pictures to display, gives you the ability (through the JavaScript library) to listen for like events so that you know in real time when a user clicks the Like button, and it always gives the user the ability to add an optional comment to the like

It has multiple attributes like href, layout, width, action etc. you can get the complete list at http://developers.facebook.com/docs/reference/plugins/like

Of course you should always try to use XFBML button only because it gives you more options and control over Iframe facebook like but again it requires Facebook JavaScript SDK in order to make it work.

Facebook JavaScript SDK:

It is open source and available on GitHub [http://github.com/facebook/connect-js]

JavaScript SDK is also necessary to use the XFBML version of facebook like.

There are 2 ways to call JavaScript SDK

  1. Just write this line in your page head section and use it
    <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
  1. Another way is to load asynchronously so it does not block loading other elements of your page:
    <div id="fb-root"></div><script>window.fbAsyncInit = function() {
    
    FB.init({appId: 'your app id', status: true, cookie: true,
    
    xfbml: true});
    
    };
    
    (function() {
    
    var e = document.createElement('script'); e.async = true;
    
    e.src = document.location.protocol +
    
    '//connect.facebook.net/en_US/all.js';
    
    document.getElementById('fb-root').appendChild(e);
    
    }());
    
    </script>
    
    

    Anyway there is already enough information about the SDK, you always can go and check at http://developers.facebook.com/docs/reference/javascript/

    YouTube JavaScript API:

    The JavaScript API allows users to control the YouTube chromeless or embedded video players via JavaScript. Calls can be made to play, pause, seek to a certain time in a video, set the volume, mute the player, and other useful functions.

    You can find more detail at http://code.google.com/apis/youtube/js_api_reference.html

    Not going to explain it further otherwise it will eat up the entire article if I start writing it here :)

    jQuery API:

    No need to explain this wonderful API on the planet, jQuery has all the things which you require for any website/portal starting from traversing, event handling, animation and AJAX though there are other robust frameworks too to compete jQuery like Dojo, ExtJS, Prototype, YUI etc.

    We will use the jQuery $.ajax wrapper which will serve our purpose to get the JSONP data from the YouTube to make video gallery and then we push the Facebook XFBML Like in the picture to get the set the like count.

    So now let’s start coding and see all things working together, have got the code snippets from YouTube API [http://code.google.com/apis/youtube/2.0/developers_guide_json.html] and converted to jQuery code.

    < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
    <head>
    <title>My Videos</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
    <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
    <script type="text/javascript">
    function loadVideo(playerUrl, autoplay) {
    	swfobject.embedSWF(
    		playerUrl + '&rel=1&border=0&fs=1&autoplay=' + 
    		(autoplay?1:0)+'&version=3', 'player', '585', '355', '9.0.0', false, 
    		false, {allowfullscreen: 'true'});
    
    		/*Parse the facebook like button*/
    		$('#like').html('<fb:like href="'+playerUrl+'" layout="button_count" show_faces="false" width="65" action="like" font="segoe ui" colorscheme="light" />')
    		if (typeof FB  != "undefined"){
    			FB.XFBML.parse(document.getElementById('like'))
    		}
    }
    
    function showMyVideos(data) {
    	var feed = data.feed;
    	var entries = feed.entry || [];
    	var html = ['<ul class="videos">'];
    	for (var i = 0; i < entries.length; i++) {
    		var entry = entries[i];
    		var title = entry.title.$t.substr(0, 20);
    		var thumbnailUrl = entries[i].media$group.media$thumbnail[0].url;
    		var playerUrl = entries[i].media$group.media$content[0].url;
    		var videoId = playerUrl.substr(playerUrl.indexOf('v/')+2, 11);			
    		playerUrl = "http://www.youtube.com/v/" + videoId;	
    		html.push('<li onclick="loadVideo(\'', playerUrl, '\', true)">',
    				  '<img src="', 
    				  thumbnailUrl, '" width="94" height="58"/>', '</ul></script></head></html></li>');
    	}
    	html.push('');
    	document.getElementById('videos').innerHTML = html.join('');
    	if (entries.length > 0) {
    		loadVideo(entries[0].media$group.media$content[0].url, false);
    	}
    }
    
    $(function(){
          $.ajax({
                type: "GET",
    			url: "http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed?time=this_week&alt=json-in-script&max-results=5&format=5",
                cache: false,
                dataType:'jsonp',
                success: function(data){
                    showMyVideos(data);
              },
    		  	error: function(XMLHttpRequest, textStatus, errorThrown, data){
    				alert("Not able to fetch the data due to feed unavailability!!!");
    			}
            });
    })
    
    
    
    <style>
    
    body{
    	background:#1d1d1d;
    	color:#c0c0c0;
    	font-family:Arial, Helvetica, sans-serif;
    	font-size:100%; 
    	line-height:1.125em;
    	}
    
    #videoContainer {
    	background:#1d1d1d;
    	border-bottom:2px solid #2a2a2a;
    	font-size:.75em;
    	height:625px;
    	overflow:hidden;
    	position:relative;
    	}
    
    #playerContainer {
    	margin:150px auto;
    	width:625px;
    	}
    
    #like {
    	height: 15px;
    	margin-top: 10px;
    	text-align: right;
    	
    	}
    
    ul.videos {
    	list-style: none;
    	margin-bottom: 1em;
    	margin-left: 0em;
    	padding-left : 0em;
    	}
    	ul.videos li {
    		cursor: pointer;
    		display: inline;
    		margin-bottom: 1em;
    		padding-right: 28px;
    	}
    
    #content{
    	backgroud:#0F0;
    	margin:0px auto;
    	width:625px;;
    	}
    	#content h1{
    		display:inline;
    		font-style:italic;
    		font-weight:normal;
    		font-size:1.2em;
    		letter-spacing:-0.7px;;
    	}
    
    </style>
    
    
    <body>
    <div id="videoContainer">
        
        <div id="playerContainer">
            <div id="player"></div>
        
    		<div id="like"></div>
       		<div id="videos"></div>
    	
    	</div>
    		</div>
    
    <div id="content">
    <h1>Mohammed Arif Blog Facebook Likes</h1>
    <fb:like href="www.mohammedarif.com" layout="button_count"></fb:like>
    </div>
    </body>
    
    

    So what we doing here is fetching YouTube data based upon some filter criteria like most_viewed, max-results and format etc in the jQuery URL parameter, there are number of criteria available in gdata feed and the dataType is JSONP which works cross domain and of course using GET method to fetch video feed.

    $(function(){
          $.ajax({
                type: "GET",
    			url: "http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed?time=this_week&alt=json-in-script&max-results=5&format=5",
                cache: false,
                dataType:'jsonp',
                success: function(data){
                    showMyVideos(data);
              },
    		  	error: function(XMLHttpRequest, textStatus, errorThrown, data){
    				alert("Not able to fetch the data due to feed unavailability!!!");
    			}
            });
    })
    

    Then we hit the success method when the request succeeds then we send the data to the next method showMyVideos(data) to parse and build the DOM.

    function showMyVideos(data) {
    	var feed = data.feed;
    	var entries = feed.entry || [];
    	var html = ['<ul class="videos">'];
    	for (var i = 0; i < entries.length; i++) {
    		var entry = entries[i];
    		var title = entry.title.$t.substr(0, 20);
    		var thumbnailUrl = entries[i].media$group.media$thumbnail[0].url;
    		var playerUrl = entries[i].media$group.media$content[0].url;
    		var videoId = playerUrl.substr(playerUrl.indexOf('v/')+2, 11);			
    		playerUrl = "http://www.youtube.com/v/" + videoId;	
    		html.push('<li onclick="loadVideo(\'', playerUrl, '\', true)">',
    				  '<img src="', 
    				  thumbnailUrl, '" width="94" height="58"/>', '');
    	}
    	html.push('</ul>');
    	document.getElementById('videos').innerHTML = html.join('');
    	if (entries.length > 0) {
    		loadVideo(entries[0].media$group.media$content[0].url, false);
    	}
    }
    
    

    Now we just need to read the data and manipulate the DOM and attach loadVideo() method with the specified URLs and also load the first video using our loadVideo(playerUrl, autoplay) method which takes 2 parameters which takes playerUrl and autoplay which we need to send to the SWFObject embedSWF() to build and run the videos.

    function loadVideo(playerUrl, autoplay) {
    	swfobject.embedSWF(
    		playerUrl + '&rel=1&border=0&fs=1&autoplay=' + 
    		(autoplay?1:0)+'&version=3', 'player', '585', '355', '9.0.0', false, 
    		false, {allowfullscreen: 'true'});
    
    		/*Parse the facebook like button*/
    		$('#like').html('<fb:like href="'+playerUrl+'" layout="button_count" show_faces="false" width="65" action="like" font="segoe ui" colorscheme="light" />')
    		if (typeof FB  != "undefined"){
    			FB.XFBML.parse(document.getElementById('like'))
    		}
    }
    

    loadVideo() is the main method to do all things including build the dynamic Facebook like widget, this is the key to write this article because making dynamic Facebook Like widget may create some problems.

    Anyway now we have the solution with us, so we already have DIV id=”like” in our HTML, we just writing XFBML on run time to parse the Facebook Like button and get and set the video count based upon the particular video.

    		/*Parse the facebook like button*/
    		$('#like').html('<fb:like href="'+playerUrl+'" layout="button_count" show_faces="false" width="65" action="like" font="segoe ui" colorscheme="light" />')
    		if (typeof FB  != "undefined"){
    			FB.XFBML.parse(document.getElementById('like'))
    		}
    

    And then we check whether FB object exist or not and if it does then parse the XFBML tag and show the count if you like it.

    Here you go to see the complete code and demo

7 observations on “Facebook Like, YouTube Video Feed and AJAX using jQuery
  1. lanner

    Hello and good job
    But i don’t understant how to modify the line gdata to show my playlist or the videos of my youtube account, if you can help me thanks :)

     
  2. lanner

    Hello

    Another problem, if you push like button of the video in your fb you have :

    CWS 6 xڝW�SGÿzf¤=yÁ¿ˆ 66cc^ƒ8Þ%h$õ€ÌhF™ ”=ìV.›SŽTí!•Û^rØ?a«ö°—½(vm\{ÝS​þï×= œØ»«‚™éïÕ¿ïÑÝ_ƒòo€èŸÂ–;úà÷]ÿ óvAŸË,¯—Ó™ÃÑý‘×-Ï%GGGGӖ½Ÿ˜œ​M$§SSã(1îÔLW;7k#ÂÀ2sòv±ì-sˆµ​œUq4¬ògFËÛ&ù3X‰™®“˜œ˜DC…

    How to correct this ?
    Thanks

     
  3. html5 web developers

    As well as attention-grabbing, You’re an too much expert blogger. I’ve joined up with ones rss feed and crunches to get from the try to find added of your amazing article. Also, I’ve discussed your site in my social support systems

     
  4. Retha

    Hi, Neat post. There’s an issue together with your website in internet explorer, would check this? IE still is the marketplace chief and a good component to people will miss your great writing due to this problem.

     

Leave Your Observation

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>