How To Capture And Track Clicks On The Facebook “Like” Button

The Facebook “Like” button is being added to more and more websites. If you also want to add the “Like” button to your website there are two possible options available. You can either use an iframe directly and generate the code on the Facebook website or use Facebook’s own XFBML extensions to HTML.

Because integration of the iframe solution is really straightforward - you can create your iframe code on the Facebook website - this article will only focus on integrating the XFBML solution which although being a bit more complex has the following advantages:

  • allows the user to add a comment as well
  • allows you to track the click on the like button

Obtaining A Facebook Application Id

First of all  have done this you have to obtain an application id (”app id”) from Facebook just as if you were to create a full Facebook app. Go to this site, enter a name for your “application”, e.g. your website domain name, agree to the terms and click on the “Create” button.

On the following page just enter the URL for your website pointing to your homepage, e.g. “http://www.saschakimmel.com/” in the field “COnnect URL”. Just make sure that the URL contains a slash at the end.

After you’ve clicked on the “Save Changes” button Facebook will show you an application id, your secret key and some more information. For the purpose of this article you only need the application id.

Adding The Core Code With Standard JavaScript

After you have obtained the application id you first of all have to add Facebook’s namespace to your html element on the website you wish to add the “Like” button to:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">

After this you have to add this code to the page on your website where you wish to add the “Like” button to. Add this add the very end of your HTML code right before the closing “</body>” tag:

<div id="fb-root"></div>
<script type="text/javascript">
<!--
window.fbAsyncInit = function() {
 FB.init({appId: 'YOUR_FACEBOOK_APP_ID', status: true, cookie: true, xfbml: true});
 FB.Event.subscribe('edge.create', function(href, widget) {
 // Do something, e.g. track the click on the "Like" button here
 alert('You just liked '+href);
 });
};
(function() {
 var e = document.createElement('script');
 e.type = 'text/javascript';
 e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
 e.async = true;
 document.getElementById('fb-root').appendChild(e);
 }());
//-->
</script>

As you can see I have highlighted three parts in red. The first one, “YOUR_FACEBOOK_APP_ID” has to be replaced with the Facebook Application Id you have generated before.

The line beginning with “alert” is where you can add your custom tracking code or whatever action you wish to happen when a user likes your website.

The text “en_US” means “English/US” and defines the locale setting. If you’ve got a German website you would use “de_DE” here etc.

So that’s basically all you have to do to support the button element with standard JavaScript.

Adding The Core Code With Prototype.Js

As you might know I’m using the Prototype.js JavaScript Framework whenever possible so I’ve created a small JavaScript class you can use if you’re using prototype.js on your website.

Just download this file and save it as facebook.js. You can then use this code on your website - just add it to the bottom of your page as well:

<script type="text/javascript" src="facebook.js"></script>
<script type="text/javascript">
<!--
Event.observe(window, 'load', function() {
        new facebookLikeButtonClass('YOUR_FACEBOOK_APP_ID', 'en_US', function(href, widgetObject) {
                // Do something, e.g. track the click on the "Like" button here
               alert('You just liked '+href);
        });
});
//-->
</script>

Adding The Button

Now that you’ve setup the core code you can just add the “Like” button wherever you want on your page by adding this code to the page where you want the button to appear:

<fb:like></fb:like>

Now that’s all!

You can set all of the attributes for the “Like” button on the tag as well just like you would set them on the Facebook page for the iframe code.

<fb:like href="URL" layout="standard|button_count" show-faces="true|false" width="450" action="like|recommend" colorscheme="light|dark" font="arial|lucida grande|segoe ui|tahoma|trebuchet ms|verdana"></fb:like>

You can just set the values accordingly. Just make sure you’re really closing the tag with the “</fb:like>”, this separate closing tag must be used and you cannot shorten the tag as you would usually do with the “/>” at the end.

Capturing “Dislikes”

You can’t capture if the user unlikes the site by clicking on the “Like” button again. The Facebook JavaScript API just doesn’t provide any event for this.

Click here for a working example

Share and Enjoy:
  • DZone
  • del.icio.us
  • Digg
  • StumbleUpon
  • Mixx
  • TwitThis
  • Technorati
  • FriendFeed
  • Google Bookmarks
  • BlinkList
  • blogmarks
  • Furl
  • LinkArena
  • Live
  • MySpace
  • NewsVine
  • Ping.fm
  • Reddit
  • Simpy
  • Spurl
  • Identi.ca
  • LinkedIn
  • MisterWong
  • Slashdot
  • Sphinn
  • Yahoo! Bookmarks
  • Facebook
  • RSS
  • Turn this article into a PDF!
  • Print this article!

Tags: , , , , ,

108 Responses to “How To Capture And Track Clicks On The Facebook “Like” Button”

  1. simon says:

    how ironic that you don’t have a like button on this article :-)

  2. admin says:

    Now it’s there :)

  3. tong says:

    I do not find the code how to do it
    can you show us plz?

  4. admin says:

    @tong: The code is in the article.

  5. tong says:

    // Do something, e.g. track the click on the “Like” button here
    Sorry I want this part of code , like how can track if the user click the button

  6. admin says:

    @tong: That depends on your knowledge, the tracking systems you’re currently using and so on. There is no “one-fits-all” solution. You could track it in virtually any programming language with any database etc.

  7. tong says:

    In fact I just want to know if the user click this like button or not if the user click it I just want set my flag to try if not just do not any thing then I need pass it to my pHP script say this guy click the like button for me .

  8. tong says:

    could you show me the code of this plz?

  9. tong says:

    any suggestions?

  10. Rick says:

    Hi Sacha
    I have an facebook app canvas rendering as FBML, and in my index.php, I’m trying to hide the div that contains the like button when it is clicked, or the user returning to the app page already like the button. I have tried to check it with FB.Event.subscribe(’edge.create’… but doesn’t work.

    Do you have any idea, how to make it work in the FBML page?

    Thanks

    code below:

    function hideDiv()
    {
    var parentDiv = document.getElementById(’likeBox’);
    parentDiv.setStyle(’visibility’, ‘hidden’);

    }
    function showDiv()
    {
    var parentDiv = document.getElementById(’likeBox’);
    parentDiv.setStyle(’visibility’, ‘visible’);
    }

    FB.init(”", “xd_receiver.htm”);

  11. admin says:

    @tong You could use prototype.js for that - http://api.prototypejs.org/ajax/ajax/request/

  12. admin says:

    @Rick: Sorry, I can’t help you with a Facebook canvas app as I have never used it. There’s a huge difference between FBML in a canvas and XFBML on a website.

  13. saokat ali says:

    How can i Capture “Like” Button on my facebook fan pages

  14. Johnson says:

    Is there an API event to capture comment box which appears after the LIKE button is being clicked?

  15. admin says:

    @Johnson: Facebook does not provide any event for this currently.

  16. Hello Sasha,

    instead of

    alert(’You just liked ‘+href);

    I would like to run a php file via ajax that inserts some values into the DB. How is this possible?

  17. Tommy says:

    Thanks for the article, I’d just like to point out the edge.create event will not be called unless your Connect URL is the same as the url you’re testing. This means you’ll need multiple applications if you want this code to work on multiple domains.

  18. admin says:

    @Tommy: THanks for pointing this out. I should have written something about that in the article. If you’re using multiple systems for testing etc. you need to create a Facebook application key for each of them.

  19. ROMAIN says:

    HELLO

    How put the likebox on my myspace, Myspace doesn’t accept iframe !!

    please help me !!!

  20. Andy Menzies says:

    Thanks a lot for posting this article - my web guys have now installed the code and all seems to be working correctly on my website. However, I’m not sure how to go about viewing what visitors ‘like’ - do you know where I can find this info?

    I can see the graph in the ‘insights’ section in my applications section on FB but there’s no data on there, even though the ‘like’ button is being used.

    Any ideas?

    Cheers,
    Andy

  21. Adrian says:

    I send an HTML email newsletter with a FB like button that points to the online version of the email: demo.mydomain.com/newsletter1.html. I would like to have a simple counter on my web application (demo.mydomain.com/applicationStats.do) that shows how many people like my newsletter. How can I do that?

    I’ve read all the documentation and I’m a bit lost to be honest. Do I need to create a Facebook Application Id for my domain and then use the facebook Graph API (or FQL?) on my site to read the number of likes? I haven’t found any explanation how to do it, if that’s the correct way.

    Any code sample or advice would be greatly appreciated!

  22. Alvaro Vargas says:

    Almost gave up trying to make xfbml like button work, but I found this, THANKS!!!!!!!.

  23. Brandon says:

    this doesnt work anymore?

  24. redherring917 says:

    Hi. I understand the concept of tracking these “Likes”, but am still lacking an actual implementation… a replacement for this “alert(’You just liked ‘+href);” that will store the click event. It’s javascript, which is client side, so i can’t write to a database at that point, because that’s server side?

    I am sure that I am not seeing the forest for the trees here.

    Thanks in advance for any assistance you can provide!

  25. admin says:

    @redherring917: You can track this with Google Analytics on the client side (see the Google analytics docs for tracking) or via the server by issuing an AJAX request like this (with prototype.js):
    new Ajax.Request(’/track.php’);

  26. redherring917 says:

    Thanks. I ended up going with an ajax request, which worked very well!

  27. admin says:

    @Brandon: From time to time Facebook has some hiccups where it doesn’t work. You can get the latest updates from Facebook here http://developers.facebook.com/live_status Anyway, what doesn’t work for you? Isn’t the event fired or isn’t the button displayed at all? Does it work again now?

  28. Thanks. A pity I found this too late, since I’ve created pages already, some of which are growing at a rapid pace. I wish FB would create a way to merge pages and apps.

  29. Adrian says:

    Any thoughts about my previous query? thanks

  30. [...] Sascha Kimmel has written a very easy to follow step-by-step guide on how to do this. Read More (0) [...]

  31. Woody Hayday says:

    This is going to become more and more imperative ;)

  32. [...] How To Capture And Track Clicks On The Facebook “Like” Button « Sascha Kimmel – Living Th… [...]

  33. [...] How To Capture And Track Clicks On The Facebook “Like” Button « Sascha Kimmel – Living Th… [...]

  34. Majstor says:

    Very nice work, thank you for that.
    I am interesting to know how to have some javascript code, which will put ‘en_US’ or ‘de_DE’, etc. regarding the users place or country…

    Greetz

  35. Majstor says:

    Hi Sacha,

    Yeah, is it 2:15 am, but I found a solution :-)

    Greetz

  36. Christian says:

    Hi Sascha, thank you very much for your article. I just want to know if I can add a PHP/MySQL code to the “Do something” section so I can track the clicks in a MySQL database. Thanx!

  37. admin says:

    @Christian: You can do whatever you like on the server side, you just have to send an AJAX request to the server with e.g. prototype.js

  38. Achim says:

    Excellent tutorial, thanks Sascha!
    It took me only half an hour to implement this kind of like button on my health related blog: http://www.ms-reporter.de and I did send my thanks to this turorial’s author via http://schnellze.it?p=1224
    Very nice work and very intermediate-friendly written article.

    PS. @admin: you can delete both URLs if you want; I’m not trying to gather links, it’s more to show real examples and a published “thank you”

  39. thene says:

    Hi, i tried this and implemented. but when i’ve already liked it previously, and i clicked on it again and im not logged on fb, the like button will popup a window so i can download, and it will update the like box to already liked it. but in that situation, the edge.create event is not fired. any thoughts? im actually using this on some situation where when its already liked, it will disappear.

    thanks

  40. umx says:

    Hey, Sascha may you help not so tech savvy people like me to tie this up with google analytics in order to access stats

  41. JB says:

    Sascha,

    Nice article! Thanks for sharing.

    Have you come across a way to detect if the user has already liked a link? I can detect this if the user has already connected to my app (http://graph.facebook.com/me/likes). If, however, they are not connected I cannot see a way to determine this. Saving to a cookie or database will not work since they can like the page on Facebook. (We set our like button URL’s to our Facebook page so we can get Fans)

    Any ideas?

    Thanks,
    Jason

  42. Wayne says:

    Hello admin,

    I just wonder how can I make use of those codes in my facebook ‘FBML’ tag.

    I mean, originally, these is a picture called A. If someone clicked the “Like” button of my facebook page/group, the picture A will be replaced by picture B in the same position.

    Is it complicated?

    I hope you may know how to solve that…..I have tried to paste those codes into “FBML” tag, but didn’t work.

  43. Wayne says:

    Solved thanks~

  44. jellert says:

    Hi,

    Thanks for the very interesting post. Before I’ll try it, is it also possible to track the I like button in analytics using a FB social module?
    Fe. on my website http://www.trendyman.be ?

    Thanks in advance !!

  45. Neil says:

    Amazing code - thanks!

  46. Rob says:

    Great stuff — this was a huge help to me!

    One question: Is anyone else having issues with this in IE 8 (including in compatibility mode)? This works perfectly for me in FF, Safari (Windows), Opera and Chrome. But with IE 8, I get a pop-up from http://www.facebook.com/connect/connect_to_external_page_widget_loggedin.php?external_page_url=

    I cannot get anything — custom tracking code, debugger or alert — to fire from inside the FB.Event.subscribe function.

    Any ideas? Thanks in advance for your time.
    Rob

  47. ularsawah says:

    How about FB comment notification…???

  48. nepal puja says:

    I understand the part about new Ajax.Request(’/track.php’);
    I am trying to put together a voting system and make sure each facebook user can vote only once.
    In track.php, I plan to keep a record of fbUID or email of the person who liked the article.
    How can I get these values passed to track.php ?

  49. admin says:

    You cannot get either the Facebook user id or the email address of the user. Facebook doesn’t offer any method for this for privacy reasons.
    You could however create an app on Facebook for your site and have your users allow you accessing this kind of data. But this is more complex and beyond the scope of this article, sorry.

Leave a Reply