• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / Getting Started With Facebook Javascript API

Getting Started With Facebook Javascript API

February 9, 2011 by Rana Ahsan 19 Comments

Facebook API Tutorials

Now a days, most of the web-based developers, whatever platform they works/specialized on (backend/front end/php/asp.net etc), do posses some JavaScript knowledge. Also, in almost all third-party apis, JavaScript implementation is very common. Facebook API isn’t different from that also. They do have a robust implementation of JavaScript API to access their data. In this tutorial, I will try to give an overview on the Facebook JavaScript api and show some examples that may help you to have a quick start.

Introduction To Facebook JavaScript SDK:

Among the all other platforms for developing Facebook application , JavaScript platform is very easy to use,integrate and light weight and can be used asynchronously, so can be used on external sites with minimal speed performance effects. There are also a several JavaScript ready code available for webmasters to use Facebook’s various functionality to integrate on their website without having to know any knowledge in JavaScript at all.

Implement Facebook Authentication Using JavaScript API:

Although, as like on other platforms, JavaScript also can access public data without any authentication, however I will start from authentication that will work as 2 in 1 solution, I guess. So, First step comes to use Facebook api is to authentication. However, although, Facebook authentication implementation on other languages like PHP/c# may seem a little complex to some developers. A matter of big relied is that, it’s really very simple and easy to implement authentication in case of JavaScript SDK. To begin, first register your Facebook application (by clicking the ‘Create New App button’). Now, go to the web page, on which, we need to implement the authentication. import the Facebook JavaScript SDK library on that page. Although it will work if you import it anywhere, but it’s always best practice to use import any js files(including this) at the bottom of the html body, just before closing the body tag(according to yahoo’s research of JavaScript performance).

use this code for importing the JavaScript SDK:

<script src="http://connect.facebook.net/en_US/all.js"></script>

Easiest way to authenticate is to use a facebook button , where user need to click for authentication. simple implimentation is as follows:

<fb:login-button autologoutlink="true" onlogin="OnRequestPermission();">
</fb:login-button>
<script language="javascript" type="text/javascript">
    FB.init({
        appId: 'Your_Application_ID',
        status: true, 
        cookie: true, 
        xfbml: true 
    });    
</script>

The above code will render as a Facebook branded button which will show whether a user is logged in or not on your application/website. If not, it will show login text, after clicking on it, a small pop-up window will appear to the user with the request permission page. After use allows the permission, this window will close, the button will show logout text as user is now logged in after allows the permission.

Now, lets focus on the different parts from the above code. “<fb:login-button autologoutlink=”true” onlogin=”OnRequestPermission();”>” is a xfbml code blog which is rendered to functional html entity by JavaScript. Of course you need to tell fb that you are going to do this and thus, you will need to set the “xfbml” parameter to “true” on initialization. If you wish, you can also use your own designed button also. FB.Init() is the method triggered at document loading and it initializes the Facebook JavaScript api with your given settings like “appid”, “xfbml” etc. By the “status” parameter, you can tell the fb api whether to check the “login status” or not. By the “cookie” parameter, you are can tell whether to use cookie for saving the session state or not. Its important in the case, where you may want something to implement via server code. In those cases server will be able to get/retrieve the session status via cookie variables.

You can also implement this login functionality on some other way, on some other events. For that, please use “FB.Login()” method.

Call To Facebook Graph API From JavaScript:

Lets take a simple example to retrieve the user information who is currently using the application. Use the code as follows:

<button name="my_full_name" onclick="ShowMyName()" value="My Name" />
<script language="javascript" type="text/javascript">
function ShowMyName() {
        FB.api("/me",
                function (response) {
                    alert('Name is ' + response.name);
                });
        
    }
</script>

The above code in turns calls the “https://graph.facebook.com/me” url and sets the returned JSON object to the ‘response’ variable. If you need to call some other type of api calls along with some parameters, then the first argument above will be a little different. Here is a javascript code samples that publish data to user’s Facebook timeline(user must have allowed ‘publis_stream’ access for this purpose. See facebook authentication guide for more about authentication details):

var message_str= 'Facebook JavaScript Graph API Tutorial';
FB.api('/me/feed', 'post', { message: message_str}, function(response) {
  if (!response || response.error) {
    alert('Couldn't Publish Data');
  } else {
    alert("Message successfully posted to your wall");
  }
});

References:

Here I have tried to give you a very basic introductory overview and examples for facebook javascript API. You can refer to the official facebook javascript API documentation for more details options you can use. Also, you will be able to test and run your javascript api code in the javascript test console. Here are the links to those resources:

  • Official Facebook Documentation On JavaScript SDK
  • Javascript Test Console For Facebook API

Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: facebook, javascript

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. Ashok Kumar says

    May 4, 2011 at 6:22 am

    Hi,

    Thank you very much to post this. It helped me a lot to complete my application.

    Thanks a lot.

    Reply
  2. chaQula says

    June 16, 2011 at 1:21 pm

    Good article. Thanks for putting this information. Great help ;-Q

    Reply
  3. html says

    August 20, 2011 at 3:01 am

    😀 thnks for the info 😉 🙁 8) (^^^) :putnam: :42: 😛

    Reply
  4. chun says

    February 22, 2012 at 12:49 am

    i got this in popup dialog : An error occurred. Please try again later.

    Reply
  5. S says

    June 23, 2012 at 11:59 am

    Awesome easy tutorial! 🙂 thanks a lot! better than facebook’s tutorial 😀

    Reply
  6. Simona says

    August 20, 2012 at 6:03 am

    It’ s definitely much better then the facebook’s one. Nice work. Clear and easy to follow tutorial.

    Reply
  7. Oriza says

    November 27, 2012 at 11:36 pm

    Thanks a lot before, how can i add some permission to access more information from users in that js code???

    Reply
  8. Adam says

    December 21, 2012 at 6:40 am

    Great post. Here is a blog post I recently wrote that explains how to actually log a user into your site using “Login with Facebook.” I was surprised that I couldn’t find a great example of how to complete the process.

    Basically, the Facebook Javascript API returns an access token to your client-side code. You can then submit that token to the server, use it to fetch the user’s Facebook UserID using the Social Graph API, which you can use as the unique ID for all users in your system (who are using Facebook credentials for login).

    https://www.modernsignal.com/overview_of_login_with_facebook

    Reply
  9. Emmanuel says

    March 15, 2013 at 11:23 am

    I searched everywhere for three days, I am glad you provided a clear and perfect explanation to this…
    Thanks a million!

    Reply
  10. ChartVista says

    March 4, 2014 at 10:22 am

    Nice Tutorial.
    Thankyou very much.

    Reply
  11. mithilesh says

    March 4, 2015 at 5:34 am

    Hello Sir, I want to add button of add photos on my web application like facebook
    And then I want to share selected image on facebook wall.
    Please give me code or Any Idea. My EmailID is gautammithilesh15@gmail.com.
    Thanks

    Reply
  12. Anon says

    September 30, 2015 at 1:49 pm

    Thank you sir, finally a post that makes sense. Facebook API docs are the stupidest and most unorganized thing i’ve ever seen. Thanks for these instructions!

    Reply
  13. Sagar Balyan says

    January 17, 2016 at 8:05 am

    Hello Ali Ahsan i really liked your post!

    But when i pasted the code of updating the status from your website, it gave me the error “Couldn’t Publish Data” which might be because of response error. Can you tell me why am i getting the error?

    Reply
  14. Parixit says

    April 16, 2016 at 2:51 am

    Hello sir,
    I’m trying to post an image on facebook page with different login not as a admin of the page. But i’m getting authorization issue. How can i achieve that using javascript API code. Please help kindly.

    Reply
  15. Raj says

    June 6, 2016 at 2:11 am

    after clearing history in firefox …im getting error “Not Logged In: You are not logged in. Please login and try again” when i try to login with facebook …can anybody help me ??

    Reply
  16. Enson Thode says

    May 9, 2017 at 4:58 am

    Hi There!
    I’m glad to finally find some example on Facebook’s Javascript SDK coding, I’m tryng to control an facebook video player embeeded on my website with no success, i just want to apply the “.pause()” method to stop the player sound from an external button (this button also hides the player and unhide another one via CSS, using jquery addClass / removeClass.
    Thank you in advance for your help.

    Reply
  17. Oleg Filchakov says

    September 6, 2018 at 1:57 pm

    Thanks BRO! I’m found this article on 15 page in gnoogle. You must be FIRST!

    Reply
  18. abdul waheed says

    May 17, 2022 at 8:30 am

    fb v13 , don’t have publish stream , it post to page, but not to timeline, what is solution ?

    Reply

Trackbacks

  1. facebook login api javascript example Account Official Log In Customer Service Contact Online Info - bankech.com says:
    December 3, 2021 at 10:42 pm

    […] Facebook Javascript API Tutorials And Code Examples […]

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Getting Started With UDP Programming in Java
    Getting Started With UDP Programming in Java
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023