How to: Integrating Facebook in your Website

Posted in Tutorials • Posted on 41 Comments

The Facebook JavaScript SDK, the one we will be using for our app, enables us to access all of the features of the Graph API via JavaScript, and it provides a rich set of features like authentication and sharing. In this tutorial I’ll show you how to use this SDK in your site. I’ll show you how to add some features to an application we built-in my previous tutorials, the distance finder (part1 of the tutorial, part2). As you might remember, we’ve also added twitter @anywhere features to the app (the tutorial), now it’s time to add Facebook as well!

What are we going to build?

We already have a distance finder, an app the uses the google maps api to find the distance and route between two locations. The results of the search can be shared on twitter. In this tutorial, I’ll show you how to share your results on Facebook!

You can check out the demo here, and also download the source code.

Prerequisites

To be able to use the Facebook JavaScript SDK, we will need an application ID. To get one, we have to register a new app. We can do this here. We will need to fill in the following info correctly to be able to use our new app:

  • in the ‘website’ tab, at ‘site url’ we must write the url where the app will be stored
  • in the ‘facebook integration’ tab, we must fill in ‘Canvas URL’, also our app’s url

A Facebook page will be generated for our app, here it is. We can personalize that by adding a description, a photo, etc.

When a user will post on his wall from an app, Facebook will write the name of the app which was used to post that message. When someone clicks on that link, they will be sent to the app’s page.

Our app’s page will also have a ‘Like’ button, if people click it, we will know who liked our app. I will also show you how to add a similar like button on the site, a button that will be connected to our app’s Facebook page.

Changes to the previous version of our app

In this tutorial I will only explain the Facebook related changes we made to our app. If you have questions regarding the rest of the code, check out the previous tutorials or drop me a message.

Including the script

To use the JavaScript Facebook SDK, we will first have to load the SDK in our site. We will do this asynchronously so it does not block loading other elements of our site. We have to add the following code after the tag:

<div id="fb-root"></div>
<script type="text/<span class="><!--mce:0--></script>
window.fbAsyncInit = function() {
   FB.init({appId: 'ADD_APP_ID_HERE', status: true, cookie: true, xfbml: true});
};
(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>

Don’t forget to fill in the API key!

What are we going to do with the script?

We are going to give our users to possibility to login to Facebook directly from our app and post their search results there.

We will first add a Facebook login button. Here’s the code from Facebook to add such a button:

<fb:login-button autologoutlink='true'  perms='email,user_birthday,status_update,publish_stream'></fb:login-button>

We will then have to register the login and logout events and also add a function to check if the user is logged in (when someone visits our site). We will add the following lines to the fbAsyncInit function:

FB.Event.subscribe('auth.login', function(response) {
   login();
});
FB.Event.subscribe('auth.logout', function(response) {
   logout();
});
FB.getLoginStatus(function(response) {
   if (response.session) {
      greet();
   }
});

We have added an event for when a user logs in the Facebook from our app, when they do, the login() function will be called.

When the user logs out, we’ll call the logout() function.

We’ve also added a function for checking the user status: getLoginStatus(). This will be called when the SDK is loaded, to check if the user is already logged in their Facebook account. The text on the Facebook button we added will change from “Login” to “Facebook logout” according to the user’s status. The greet() function will be called when the user is already logged in. Let’s see how the login (), logout() and greet() functions look like:

function login(){
   FB.api('/me', function(response) {
      alert('You have successfully logged in, '+response.name+"!");
   });
}
function logout(){
   alert('You have successfully logged out!');
}
function greet(){
   FB.api('/me', function(response) {
      alert('Welcome, '+response.name+"!");
   });
}

The login function saves the user’s name from the response it got from facebook and displays a message on the screen. The logout and greet button are also just used to show messages on the screen.

After adding these, our user will be able to log in to their facebook account directly from our app! If the user is logged in their facebook account when they visit our app, they will be greeted.

Now let’s see how to help them share their search results!

Adding the share box

We will add a comment box similar to the one added for twitter, next to that one.

In the continueShowRoute() function we will add some more code, to also add a facebook comment box to our ‘share’ div:

var twitter = "<div class='comments' style='display: inline-block;'></div>";
var facebook = "";
document.getElementById("share").innerHTML = twitter+" "+facebook;

As you remember, we used the share_twitter() function to create the link to share and show the comment box with the message. We will be adding there the code to also show the facebook box.

var code = "<span style="font-size: large;">Share with your facebook friends!</span>";
code += "

<input id="status" size="60" type="text" value=" My search on <span class=&quot;hiddenSpellError&quot; pre=&quot;on &quot;>distancefinder</span>: &quot;+response+&quot;" />";
code += "<br/><a href='#' onclick='setStatus(); return false;'>Share!</a>";
document.getElementById('facebook').innerHTML = code;

The facebook box will have an input field with the text and link to be shared and a ‘Share!’ link. As you can see, when the users click on the ‘Share!’ link, the setStatus() function will be called. Let’s see what it does:

function setStatus(){
   // check if user is logged in:
   FB.getLoginStatus(function(response) {
      if (response.session) {
         new_status = document.getElementById('status').value;
         FB.api(
         {
            method: 'status.set',
            status: new_status
         },
         function(response) {
            if (response == 0){
               alert('Your facebook status was not updated.');
            }
            else{
               alert('Your facebook status was updated');
            }
         }
     );
     } else {
        alert('please log in first :)');
     }
   });
}

It first checks if the user is logged in. For this, it uses the getLoginStatus() function from the javascript SDK. If the user is not logged in, we’ll show a message informing them that they must login in order to share the search results.

If the user is logged in, we get the message to share from the input field called ‘status’, and use the status.set method from the SDK to set the user’s status to the new value. After setting the status, we will show a message to the user.

And that’s it! Our users can now share their search results on facebook!

Adding the ‘Like’ box

You might have noticed there’s a like box in our app, below the map. It shows the users that have liked our facebook app. To add one of those, all you have to do is go to the app profile page, at the “get started” tab. There you will find a link to create a like box. You can choose some options for your box and facebook will generate the code for you. The code for the box from our app looks like this:

<fb:like-box profile_id="APP_ID_IS_HERE" stream="false" header="false"></fb:like-box>

It really simple, isn’t it?

I hope you enjoyed this tutorial and don’t hesitate to ask if you have any questions.

Warning

This might not work well with internet explorer. I’ve tested with chrome, firefox and opera and it works great on those!

7 Written ArticlesWebsite

Irina is a software developer from Bucharest, Romania. She enjoys working on various programming projects. She likes spending her spare time reading, hiking, travelling, skating or playing tennis. She also blogs a bit. You can find her online in her home on the internet and on twitter.

41 Comments Best Comments First
  • Taimur Asghar

    Thursday, September 16th, 2010 19:03

    5

    Good stuff here !

    +2
  • Naweed

    Monday, February 6th, 2012 07:51

    36

    Nice post, it was very much helped e to integrate FB login button in my website. Thank you.

    +1
  • Kashif

    Friday, March 25th, 2011 06:29

    15

    Hey man , this was really good, shud help me in my website

    0
  • Aaron

    Wednesday, March 16th, 2011 09:07

    14

    I added the code but its not giving exact permission rights to my users which they get with the default login…how to resolve this??

    0
  • Kashif

    Saturday, March 26th, 2011 07:41

    16

    hey , do you also know how to upload a picture on facebook using javascript?

    0
    • Kashif

      Saturday, March 26th, 2011 07:43

      17

      I need this for my website. Basically, I display a google map in a particular div in my website. I need to share this on the user’s facebook profile as image. Is there a way to convert this google map as image and then upload this on users facebook profile using javascript?

      -1
      • Irina

        Wednesday, May 4th, 2011 14:47

        18

        Hi. I do not know of an easy way of doing this. I’m sorry.

        -1
  • Kannan

    Wednesday, September 15th, 2010 17:41

    1

    Very detailed tutorial. The iframe version will work on all browsers. Thanks for sharing.

    0
    • Irina

      Thursday, September 16th, 2010 11:17

      3

      I’m glad you liked my tutorial!

      Thanks for the tip :)

      -3
      • rishi

        Monday, February 21st, 2011 05:37

        13

        This is the best example I have seen in web by far. Better than facebook’s documentation examples. Really great job!

        0
  • Anderson

    Wednesday, July 6th, 2011 00:36

    20

    excelente tutorial, muito obrigado por compartilhar.

    0
  • Mandy

    Wednesday, May 25th, 2011 08:26

    19

    Irina,

    I like your tutorial.
    My login popup logs people into fb, but nothing else!
    I will try your code.

    0
    • Irina

      Wednesday, August 24th, 2011 10:31

      22

      I’m glad you find it useful. If you need any help just ask!

      0
  • David

    Thursday, February 3rd, 2011 22:28

    12

    Thanks this helped so much

    0
  • LeeAnn

    Friday, October 8th, 2010 16:32

    6

    Great tutorial! I am just diving into FB development and struggling with the lack of good examples in the API so these kinds of things really help.

    I am trying to develop an application that will list the upcoming events that a user is attending. I have an admin account for my site’s public page that I set as attending the events on the page. I can get the user’s name to print to the screen, and the event’s name (when I hard-code the eid), but when I call the event_member table to get the “attending” relationship, that’s where it fails. If you are willing I could really use some experienced insight on my code! I’ve posted it here: http://stackoverflow.com/questions/1338488/outside-access-to-facebook-events/3876186#3876186

    Is there a forum you could recommend for help with FB development?

    0
    • Irina

      Tuesday, October 12th, 2010 09:25

      7

      Unfortunately I haven’t found some really good examples on working with the fb api :(

      I’ve never tried that before, but I’ll take a look at your code.

      0
  • Irina

    Thursday, September 16th, 2010 11:17

    2

    Thanks! I’m glad you liked it!

    0
  • mosaic

    Wednesday, October 27th, 2010 16:29

    8

    There’s also a way to copy and paste a javascript snippet into your site for a Facebook Connect button. http://toolkit.launchbit.com It’s pretty simple and people can use it to login. You can also see who’s been logging in with Facebook.

    0
  • Brett Widmann

    Thursday, January 27th, 2011 22:26

    11

    This was really helpful. This worked really well.

    0
  • Wilkovacs

    Monday, January 10th, 2011 20:41

    10

    I want to display SOMEONE ELSE’S Facebook entries on my website.
    I sell Yamaha outboard boat motors. I want to have Yamaha’s Outboard Facebook page with its latest entries displayed on MY websites home page. Any suggestions on how to do this?

    0
  • tylerlin 

    Tuesday, November 2nd, 2010 12:02

    9

    This is very useful. Thank You.

    0
  • Ryan Speakman

    Friday, August 5th, 2011 17:27

    21

    Been at this for three days straight. I’ve studied every single word of this tutorial and cross-referenced with Facebook’s own info, etc. I’m still completely and totally lost (and I’ve been a full-time programmer for 16 years!!)… I believe that everything is in place as it should be, but FB.getLoginStatus refuses to return anything but null: I get nothing but the “please log in first :)” over and over and over again (in both Firefox and IE). I have “Like” and “Share” buttons on the same page as this code, and those detect that I’m logged into Facebook just fine (in both browsers). I can’t figure out for the life of me what I’m doing wrong. Any chance that you’d be willing to take a look at my code, etc.?

    0
    • Irina

      Wednesday, August 24th, 2011 10:32

      23

      Hi

      Sure, I can take a look at the code. Please email me and I’ll try to help :)

      0
  • kishore

    Thursday, December 1st, 2011 17:26

    32

    I have created a facebook fan page for my blog, but the thing is that it is asking me 25 likes to create a page like facebook.com/mysite.com.

    Is there any way to avoid this restriction?

    My site is newly launched, as of now 25 like take some more time(uncertain).

    0
  • Anonymous

    Monday, January 16th, 2012 21:33

    35

    Someone essentially help to make critically articles I would state. That is the first time I frequented your website page and thus far? I amazed with the analysis you made to make this actual put up incredible. Excellent task!

    0
  • johnny

    Thursday, December 29th, 2011 05:03

    34

    Thank you very much for the help. I couldn’t make facebook login work without your tutorial. Thanks again!!!

    0
  • Bhuvan

    Wednesday, February 8th, 2012 08:46

    37

    Hi
    Thanks for your code.

    I already created some files and also I downloaded your code and hosted in my server too but all the code shows the same error messages.
    can you help me in this.
    Its very urgent for my project to complete.

    when i press the login it open the popup with this url and display the error “An error occurred. Please try again later.”

    0
    • Harry Lin

      Tuesday, May 1st, 2012 19:41

      41

      You do facebook intergration in 10 min with the efpa library, efpa stand for (Easy Facebook PHP API), the library was written to make facebook intergration easy and usable by anyone.
      This is the main page for the library http://labs.gurron.com/projects.php?proj=efpa

      It has documentation and a youtbe tutorial videos showing you from A to Z how this can be achieved.
      http://labs.gurron.com/projects.php?proj=efpa&pg=docs

      I think this may be perfect for you. They also have a bugs and issues page where you post any issue you find have and they’ll solve it, or you can go on Stack Overflow and use the #efpa tag to ask your question and they’ll respond pretty quick.

      0
  • nobody

    Monday, March 26th, 2012 08:57

    38

    when i press teh login button it shows teh same error reported by bhuvan above..please reply asap

    0
  • Priyanka

    Wednesday, April 4th, 2012 03:32

    39

    Very relevant any upto the point information given by author on facebook integration.

    0
  • Jon

    Friday, December 16th, 2011 15:38

    33

    Great tutorial.. It helped me to put facebook connect button on my website..

    Thank you for this..

    0
  • RTWoltz

    Saturday, September 10th, 2011 18:33

    27

    Had some problems with the code but it seems to be working just fine now. The button does not want to appear for logging in or out sometimes. YES IE.

    0
  • Darren

    Thursday, December 1st, 2011 10:07

    31

    Such a nice tutorial. Does it support vb?

    0
  • Java Coder

    Friday, August 26th, 2011 15:07

    25

    Very good tutorial. This tutorial saved a lot of time for me. Thanks.

    0
  • Andre

    Friday, August 26th, 2011 03:10

    24

    hi, wherre should I put my id secret? and canvas? cause im getting error.
    This is the error: API Error Code: 191
    API Error Description: The specified URL is not owned by the application
    Error Message: redirect_uri is not owned by the application.

    0
  • abhishek

    Wednesday, September 7th, 2011 19:28

    26

    tht was one of its kind tutorial…loved it…well Irina i would still request a favour…scene is …I am a IT student..and m designing a website for a firm on php i would like to add modules related with FB and here is the part m completely lost…..can u suggest something….any rough idea would also work…..

    0
  • Yosh

    Sunday, October 9th, 2011 14:14

    29

    API Error Code: 191
    API Error Description: The specified URL is not owned by the application
    Error Message: redirect_uri is not owned by the application.

    what i do for this .. i fill all informatin right

    0
  • sridhar

    Friday, September 16th, 2011 20:46

    28

    I have used ur source code., its really very helpful to me.,.thanks alot./,., and i have a small doubt like how can we get the complete details of the particular user who has logged in like their username and pages details…Can you sort out this issue

    0
  • Ranjan

    Tuesday, November 29th, 2011 23:00

    30

    Hello sir, this script worked like a charm for me..
    but i wanted to know that how will i be able to acess the user data from the facebook to save it in my own database on first login..??

    0
  • Tim Soulo

    Thursday, September 16th, 2010 13:21

    4

    Great facebook tutorial Irina. I’ve been searching for a solution to integrate a Share button on my blog page but failed with this few weeks ago. Happy to find your tutorial through designfloat.

    -1
  • Priyanka

    Wednesday, April 4th, 2012 03:32

    39

    Very relevant any upto the point information given by author on facebook integration.

    0
  • nobody

    Monday, March 26th, 2012 08:57

    38

    when i press teh login button it shows teh same error reported by bhuvan above..please reply asap

    0
  • Bhuvan

    Wednesday, February 8th, 2012 08:46

    37

    Hi
    Thanks for your code.

    I already created some files and also I downloaded your code and hosted in my server too but all the code shows the same error messages.
    can you help me in this.
    Its very urgent for my project to complete.

    when i press the login it open the popup with this url and display the error “An error occurred. Please try again later.”

    0
    • Harry Lin

      Tuesday, May 1st, 2012 19:41

      41

      You do facebook intergration in 10 min with the efpa library, efpa stand for (Easy Facebook PHP API), the library was written to make facebook intergration easy and usable by anyone.
      This is the main page for the library http://labs.gurron.com/projects.php?proj=efpa

      It has documentation and a youtbe tutorial videos showing you from A to Z how this can be achieved.
      http://labs.gurron.com/projects.php?proj=efpa&pg=docs

      I think this may be perfect for you. They also have a bugs and issues page where you post any issue you find have and they’ll solve it, or you can go on Stack Overflow and use the #efpa tag to ask your question and they’ll respond pretty quick.

      0
  • Naweed

    Monday, February 6th, 2012 07:51

    36

    Nice post, it was very much helped e to integrate FB login button in my website. Thank you.

    +1
  • Anonymous

    Monday, January 16th, 2012 21:33

    35

    Someone essentially help to make critically articles I would state. That is the first time I frequented your website page and thus far? I amazed with the analysis you made to make this actual put up incredible. Excellent task!

    0
  • johnny

    Thursday, December 29th, 2011 05:03

    34

    Thank you very much for the help. I couldn’t make facebook login work without your tutorial. Thanks again!!!

    0
  • Jon

    Friday, December 16th, 2011 15:38

    33

    Great tutorial.. It helped me to put facebook connect button on my website..

    Thank you for this..

    0
  • kishore

    Thursday, December 1st, 2011 17:26

    32

    I have created a facebook fan page for my blog, but the thing is that it is asking me 25 likes to create a page like facebook.com/mysite.com.

    Is there any way to avoid this restriction?

    My site is newly launched, as of now 25 like take some more time(uncertain).

    0
  • Darren

    Thursday, December 1st, 2011 10:07

    31

    Such a nice tutorial. Does it support vb?

    0
  • Ranjan

    Tuesday, November 29th, 2011 23:00

    30

    Hello sir, this script worked like a charm for me..
    but i wanted to know that how will i be able to acess the user data from the facebook to save it in my own database on first login..??

    0
  • Yosh

    Sunday, October 9th, 2011 14:14

    29

    API Error Code: 191
    API Error Description: The specified URL is not owned by the application
    Error Message: redirect_uri is not owned by the application.

    what i do for this .. i fill all informatin right

    0
  • sridhar

    Friday, September 16th, 2011 20:46

    28

    I have used ur source code., its really very helpful to me.,.thanks alot./,., and i have a small doubt like how can we get the complete details of the particular user who has logged in like their username and pages details…Can you sort out this issue

    0
  • RTWoltz

    Saturday, September 10th, 2011 18:33

    27

    Had some problems with the code but it seems to be working just fine now. The button does not want to appear for logging in or out sometimes. YES IE.

    0
  • abhishek

    Wednesday, September 7th, 2011 19:28

    26

    tht was one of its kind tutorial…loved it…well Irina i would still request a favour…scene is …I am a IT student..and m designing a website for a firm on php i would like to add modules related with FB and here is the part m completely lost…..can u suggest something….any rough idea would also work…..

    0
  • Java Coder

    Friday, August 26th, 2011 15:07

    25

    Very good tutorial. This tutorial saved a lot of time for me. Thanks.

    0
  • Andre

    Friday, August 26th, 2011 03:10

    24

    hi, wherre should I put my id secret? and canvas? cause im getting error.
    This is the error: API Error Code: 191
    API Error Description: The specified URL is not owned by the application
    Error Message: redirect_uri is not owned by the application.

    0
  • Ryan Speakman

    Friday, August 5th, 2011 17:27

    21

    Been at this for three days straight. I’ve studied every single word of this tutorial and cross-referenced with Facebook’s own info, etc. I’m still completely and totally lost (and I’ve been a full-time programmer for 16 years!!)… I believe that everything is in place as it should be, but FB.getLoginStatus refuses to return anything but null: I get nothing but the “please log in first :)” over and over and over again (in both Firefox and IE). I have “Like” and “Share” buttons on the same page as this code, and those detect that I’m logged into Facebook just fine (in both browsers). I can’t figure out for the life of me what I’m doing wrong. Any chance that you’d be willing to take a look at my code, etc.?

    0
    • Irina

      Wednesday, August 24th, 2011 10:32

      23

      Hi

      Sure, I can take a look at the code. Please email me and I’ll try to help :)

      0
  • Anderson

    Wednesday, July 6th, 2011 00:36

    20

    excelente tutorial, muito obrigado por compartilhar.

    0
  • Mandy

    Wednesday, May 25th, 2011 08:26

    19

    Irina,

    I like your tutorial.
    My login popup logs people into fb, but nothing else!
    I will try your code.

    0
    • Irina

      Wednesday, August 24th, 2011 10:31

      22

      I’m glad you find it useful. If you need any help just ask!

      0
  • Kashif

    Saturday, March 26th, 2011 07:41

    16

    hey , do you also know how to upload a picture on facebook using javascript?

    0
    • Kashif

      Saturday, March 26th, 2011 07:43

      17

      I need this for my website. Basically, I display a google map in a particular div in my website. I need to share this on the user’s facebook profile as image. Is there a way to convert this google map as image and then upload this on users facebook profile using javascript?

      -1
      • Irina

        Wednesday, May 4th, 2011 14:47

        18

        Hi. I do not know of an easy way of doing this. I’m sorry.

        -1
  • Kashif

    Friday, March 25th, 2011 06:29

    15

    Hey man , this was really good, shud help me in my website

    0
  • Aaron

    Wednesday, March 16th, 2011 09:07

    14

    I added the code but its not giving exact permission rights to my users which they get with the default login…how to resolve this??

    0
  • David

    Thursday, February 3rd, 2011 22:28

    12

    Thanks this helped so much

    0
  • Brett Widmann

    Thursday, January 27th, 2011 22:26

    11

    This was really helpful. This worked really well.

    0
  • Wilkovacs

    Monday, January 10th, 2011 20:41

    10

    I want to display SOMEONE ELSE’S Facebook entries on my website.
    I sell Yamaha outboard boat motors. I want to have Yamaha’s Outboard Facebook page with its latest entries displayed on MY websites home page. Any suggestions on how to do this?

    0
  • tylerlin 

    Tuesday, November 2nd, 2010 12:02

    9

    This is very useful. Thank You.

    0
  • mosaic

    Wednesday, October 27th, 2010 16:29

    8

    There’s also a way to copy and paste a javascript snippet into your site for a Facebook Connect button. http://toolkit.launchbit.com It’s pretty simple and people can use it to login. You can also see who’s been logging in with Facebook.

    0
  • LeeAnn

    Friday, October 8th, 2010 16:32

    6

    Great tutorial! I am just diving into FB development and struggling with the lack of good examples in the API so these kinds of things really help.

    I am trying to develop an application that will list the upcoming events that a user is attending. I have an admin account for my site’s public page that I set as attending the events on the page. I can get the user’s name to print to the screen, and the event’s name (when I hard-code the eid), but when I call the event_member table to get the “attending” relationship, that’s where it fails. If you are willing I could really use some experienced insight on my code! I’ve posted it here: http://stackoverflow.com/questions/1338488/outside-access-to-facebook-events/3876186#3876186

    Is there a forum you could recommend for help with FB development?

    0
    • Irina

      Tuesday, October 12th, 2010 09:25

      7

      Unfortunately I haven’t found some really good examples on working with the fb api :(

      I’ve never tried that before, but I’ll take a look at your code.

      0
  • Taimur Asghar

    Thursday, September 16th, 2010 19:03

    5

    Good stuff here !

    +2
  • Tim Soulo

    Thursday, September 16th, 2010 13:21

    4

    Great facebook tutorial Irina. I’ve been searching for a solution to integrate a Share button on my blog page but failed with this few weeks ago. Happy to find your tutorial through designfloat.

    -1
  • Irina

    Thursday, September 16th, 2010 11:17

    2

    Thanks! I’m glad you liked it!

    0
  • Kannan

    Wednesday, September 15th, 2010 17:41

    1

    Very detailed tutorial. The iframe version will work on all browsers. Thanks for sharing.

    0
    • Irina

      Thursday, September 16th, 2010 11:17

      3

      I’m glad you liked my tutorial!

      Thanks for the tip :)

      -3
      • rishi

        Monday, February 21st, 2011 05:37

        13

        This is the best example I have seen in web by far. Better than facebook’s documentation examples. Really great job!

        0

Comments are closed.

54.83.103.17 - unknown - unknown - US