New JavaScript SDK & OAuth 2.0 based FBConnect Tutorial

facebookToday Facebook released their updated JavaScript SDK. Now the authentication system is based on OAuth 2.0 and HTTPS. So I updated my previous tutorial by writing this new post. In this post I’ll show you using javascript how could you easily integrate facebook connect (login/logout) features in your site. Additionally how to use Facebook API to get user’s information. Here I only used JavaScript no back-end PHP or any server side language.

In this tutorial I’ll explain:

  1. Facebook Authentication Process
  2. Facebook new JavaScript Usage
  3. Facebook Connect Authentication
  4. How to get extended permission to get more informations
  5. How to use graph api
  6. How to show stream publish prompt and share prompt
  7. How to publish post in user’s wall using graph api
  8. How to get additional information by FQL Query
  9. How to set status using old legacy api (REST api) calling
  10. How to show ajax loader when interactive with facebook

Before proceeding:
Demo App

1.    Facebook Authentication Process

This is how facebook authorization process will work. We will follow this process in code.

2.    Facebook new JavaScript Usage

So in the figure you are seeing how authentication will work in your site. Now we will implement that. Firstly you’ve to setup a facebook application to get the application id. You can setup application from here. Or if you have already setup a facebook application then just copy the application id and replace with xxxxxxxxxxx. Remember oauth: true is new addition in this latest javascript sdk that enables your site for OAuth 2.0 authentication.

window.fbAsyncInit = function() {
        FB.init({ appId: 'Your_APP_ID',
            status: true,
            cookie: true,
            xfbml: true,
            oauth: true});

        showLoader(true);

        function updateButton(response) {
            button       =   document.getElementById('fb-auth');
            userInfo     =   document.getElementById('user-info');

            if (response.authResponse) {
                //user is already logged in and connected
                FB.api('/me', function(info) {
                    login(response, info);
                });

                button.onclick = function() {
                    FB.logout(function(response) {
                        logout(response);
                    });
                };
            } else {
                //user is not connected to your app or logged out
                button.innerHTML = 'Login';
                button.onclick = function() {
                    showLoader(true);
                    FB.login(function(response) {
                        if (response.authResponse) {
                            FB.api('/me', function(info) {
                                login(response, info);
                            });
                        } else {
                            //user cancelled login or did not grant authorization
                            showLoader(false);
                        }
                    }, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
                }
            }
        }

        // run once with current status and whenever the status changes
        FB.getLoginStatus(updateButton);
        FB.Event.subscribe('auth.statusChange', updateButton);
    };
    (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);
    }());

This is the most efficient way to load the javascript SDK in your web site. And in this way the sdk will load asynchronously so it does not block loading other elements of your page. Details of FB.init method.

And your html tag should be

<!DOCTYPE html>
<html xmlns:fb="https://www.facebook.com/2008/fbml">

3.    Facebook Connect Authentication

On the first part of the code you will see 2 Facebook api functions called

FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);

After loading the facebook javascript library, this method getLoginStatus() called and checked the user authentication status and it will send the response to updateButton() method.

FB.Event.subscribe() this method registered the auth.statusChange with facebook. That means if user successfully login or authorized your app or logout or cancel login process, it will trace that and call updateButton() method with the response. In this updateButton() method you’ll see the code of authentication that follows the first figure. In the full source code you’ll see 2 additional methods

    function login(response, info){
        if (response.authResponse) {
            var accessToken                                =   response.authResponse.accessToken;

            userInfo.innerHTML                             = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name
                + "<br /> Your Access Token: " + accessToken;
            button.innerHTML                               = 'Logout';
            showLoader(false);
            document.getElementById('other').style.display = "block";
        }
    }

    function logout(response){
        userInfo.innerHTML                             =   "";
        document.getElementById('debug').innerHTML     =   "";
        document.getElementById('other').style.display =   "none";
        showLoader(false);
    }

Those are called when user successfully login and authorized your app and when user logout.

4.    How to get extended permission to get more informations

On the first part of the code you’ll see the code that will run when user click login.

//user is not connected to your app or logged out
    button.innerHTML = 'Login';
    button.onclick = function() {
        showLoader(true);
        FB.login(function(response) {
            if (response.authResponse) {
                FB.api('/me', function(info) {
                    login(response, info);
                });
            } else {
                //user cancelled login or did not grant authorization
                showLoader(false);
            }
        }, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
    }

In this part you’ll see scope where you can provide extended permission parameters name. Don’t provide all permissions, only think which information you may need for your site. Here is details about permissions.

{scope:'email,user_birthday,status_update,publish_stream,user_about_me'}

5.    How to use graph api

In the new javascript sdk, the authentication code is only changed, everything else remains same. To fully understand graph api visit the link . Now i’ll show you, how to use graph api using javascript sdk. There is a method FB.api . Using this method you can call graph api.

FB.api('/me', function(response) {
  alert(response.name);
});

By calling this method it will show logged in user name. For another example check 7 number point.

6.    How to show stream publish prompt and share prompt

There is another javascript sdk method named FB.ui. Using the code you can prompt user for stream publish or share your page.

function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
        showLoader(true);
        FB.ui(
        {
            method: 'stream.publish',
            message: '',
            attachment: {
                name: name,
                caption: '',
                description: (description),
                href: hrefLink
            },
            action_links: [
                { text: hrefTitle, href: hrefLink }
            ],
            user_prompt_message: userPrompt
        },
        function(response) {
            showLoader(false);
        });

    }

    function share(){
        showLoader(true);
        var share = {
            method: 'stream.share',
            u: 'http://thinkdiff.net/'
        };

        FB.ui(share, function(response) {
            showLoader(false);
            console.log(response);
        });
    }

You’ve to provide parameters when you call streamPublish() method.

    function showStream(){
        FB.api('/me', function(response) {
            //console.log(response.id);
            streamPublish(response.name, 'I like the articles of Thinkdiff.net', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
        });
    }

7.    How to publish post in user’s wall using graph api

In my demo you’ll see another customized method named graphStreamPublish(). This is also a graph api example.

function graphStreamPublish(){
        showLoader(true);

        FB.api('/me/feed', 'post',
        {
            message     : "I love thinkdiff.net for facebook app development tutorials",
            link        : 'http://ithinkdiff.net',
            picture     : 'http://thinkdiff.net/iphone/lucky7_ios.jpg',
            name        : 'iOS Apps & Games',
            description : 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'

        },
        function(response) {
            showLoader(false);

            if (!response || response.error) {
                alert('Error occured');
            } else {
                alert('Post ID: ' + response.id);
            }
        });
    }

This method uses FB.api() and does a HTTP POST request to http://graph.facebook.com/me/feed url with some parameters to publish a feed on user’s wall.

8.    How to get additional information by FQL Query

Facebook Query Language  enables you to use a SQL-style interface to query the data exposed by the Graph API. It provides for some advanced features not available in the Graph API, including batching multiple queries into a single call. Checkout the tables to know which data of facebook user you can retrieve. In the demo’s source code you’ll see

function fqlQuery(){
        showLoader(true);

        FB.api('/me', function(response) {
            showLoader(false);

            //http://developers.facebook.com/docs/reference/fql/user/
            var query       =  FB.Data.query('select name, profile_url, sex, pic_small from user where uid={0}', response.id);
            query.wait(function(rows) {
                document.getElementById('debug').innerHTML =
                    'FQL Information: '+  "<br />" +
                    'Your name: '      +  rows[0].name                                                            + "<br />" +
                    'Your Sex: '       +  (rows[0].sex!= undefined ? rows[0].sex : "")                            + "<br />" +
                    'Your Profile: '   +  "<a href='" + rows[0].profile_url + "'>" + rows[0].profile_url + "</a>" + "<br />" +
                    '<img src="'       +  rows[0].pic_small + '" alt="" />' + "<br />";
            });
        });
    }

9. How to set status using old legacy api (REST api) calling

You can still use the old legacy api. In my demo you’ll see a text box, write something and click ‘Status Set Using Legacy Api Call’ You’ll see your facebook status will update.

function setStatus(){
        showLoader(true);

        status1 = document.getElementById('status').value;
        FB.api(
        {
            method: 'status.set',
            status: status1
        },
        function(response) {
            if (response == 0){
                alert('Your facebook status not updated. Give Status Update Permission.');
            }
            else{
                alert('Your facebook status updated');
            }
            showLoader(false);
        }
    );
}

10. How to show ajax loader when interactive with facebook

In the source code you will see a method showLoader(), and you’ll see several places of the source code this method is called.

 function showLoader(status){
        if (status)
            document.getElementById('loader').style.display = 'block';
        else
            document.getElementById('loader').style.display = 'none';
    }

Full Source Code of this project. Or direct download from github

<!DOCTYPE html>
<html xmlns:fb="https://www.facebook.com/2008/fbml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>New JavaScript SDK & OAuth 2.0 based FBConnect Tutorial | Thinkdiff.net</title>
        <!--
            @author: Mahmud Ahsan (http://mahmud.thinkdiff.net)
        -->
    </head>
    <body>
        <div id="fb-root"></div>
        <script type="text/javascript">
            var button;
            var userInfo;

            window.fbAsyncInit = function() {
                FB.init({ appId: 'YOUR_APP_ID',
                    status: true,
                    cookie: true,
                    xfbml: true,
                    oauth: true});

               showLoader(true);

               function updateButton(response) {
                    button       =   document.getElementById('fb-auth');
                    userInfo     =   document.getElementById('user-info');

                    if (response.authResponse) {
                        //user is already logged in and connected
                        FB.api('/me', function(info) {
                            login(response, info);
                        });

                        button.onclick = function() {
                            FB.logout(function(response) {
                                logout(response);
                            });
                        };
                    } else {
                        //user is not connected to your app or logged out
                        button.innerHTML = 'Login';
                        button.onclick = function() {
                            showLoader(true);
                            FB.login(function(response) {
                                if (response.authResponse) {
                                    FB.api('/me', function(info) {
                                        login(response, info);
                                    });
                                } else {
                                    //user cancelled login or did not grant authorization
                                    showLoader(false);
                                }
                            }, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
                        }
                    }
                }

                // run once with current status and whenever the status changes
                FB.getLoginStatus(updateButton);
                FB.Event.subscribe('auth.statusChange', updateButton);
            };
            (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);
            }());

            function login(response, info){
                if (response.authResponse) {
                    var accessToken                                 =   response.authResponse.accessToken;

                    userInfo.innerHTML                             = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name
                                                                     + "<br /> Your Access Token: " + accessToken;
                    button.innerHTML                               = 'Logout';
                    showLoader(false);
                    document.getElementById('other').style.display = "block";
                }
            }

            function logout(response){
                userInfo.innerHTML                             =   "";
                document.getElementById('debug').innerHTML     =   "";
                document.getElementById('other').style.display =   "none";
                showLoader(false);
            }

            //stream publish method
            function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
                showLoader(true);
                FB.ui(
                {
                    method: 'stream.publish',
                    message: '',
                    attachment: {
                        name: name,
                        caption: '',
                        description: (description),
                        href: hrefLink
                    },
                    action_links: [
                        { text: hrefTitle, href: hrefLink }
                    ],
                    user_prompt_message: userPrompt
                },
                function(response) {
                    showLoader(false);
                });

            }
            function showStream(){
                FB.api('/me', function(response) {
                    //console.log(response.id);
                    streamPublish(response.name, 'I like the articles of Thinkdiff.net', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
                });
            }

            function share(){
                showLoader(true);
                var share = {
                    method: 'stream.share',
                    u: 'http://thinkdiff.net/'
                };

                FB.ui(share, function(response) {
                    showLoader(false);
                    console.log(response);
                });
            }

            function graphStreamPublish(){
                showLoader(true);

                FB.api('/me/feed', 'post',
                    {
                        message     : "I love thinkdiff.net for facebook app development tutorials",
                        link        : 'http://ithinkdiff.net',
                        picture     : 'http://thinkdiff.net/iphone/lucky7_ios.jpg',
                        name        : 'iOS Apps & Games',
                        description : 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'

                },
                function(response) {
                    showLoader(false);

                    if (!response || response.error) {
                        alert('Error occured');
                    } else {
                        alert('Post ID: ' + response.id);
                    }
                });
            }

            function fqlQuery(){
                showLoader(true);

                FB.api('/me', function(response) {
                    showLoader(false);

                    //http://developers.facebook.com/docs/reference/fql/user/
                    var query       =  FB.Data.query('select name, profile_url, sex, pic_small from user where uid={0}', response.id);
                    query.wait(function(rows) {
                       document.getElementById('debug').innerHTML =
                         'FQL Information: '+  "<br />" +
                         'Your name: '      +  rows[0].name                                                            + "<br />" +
                         'Your Sex: '       +  (rows[0].sex!= undefined ? rows[0].sex : "")                            + "<br />" +
                         'Your Profile: '   +  "<a href='" + rows[0].profile_url + "'>" + rows[0].profile_url + "</a>" + "<br />" +
                         '<img src="'       +  rows[0].pic_small + '" alt="" />' + "<br />";
                     });
                });
            }

            function setStatus(){
                showLoader(true);

                status1 = document.getElementById('status').value;
                FB.api(
                  {
                    method: 'status.set',
                    status: status1
                  },
                  function(response) {
                    if (response == 0){
                        alert('Your facebook status not updated. Give Status Update Permission.');
                    }
                    else{
                        alert('Your facebook status updated');
                    }
                    showLoader(false);
                  }
                );
            }

            function showLoader(status){
                if (status)
                    document.getElementById('loader').style.display = 'block';
                else
                    document.getElementById('loader').style.display = 'none';
            }

        </script>

        <h3>New JavaScript SDK & OAuth 2.0 based FBConnect Tutorial | Thinkdiff.net</h3>
        <button id="fb-auth">Login</button>
        <div id="loader" style="display:none">
            <img src="ajax-loader.gif" alt="loading" />
        </div>
        <br />
        <div id="user-info"></div>
        <br />
        <div id="debug"></div>

        <div id="other" style="display:none">
            <a href="#" onclick="showStream(); return false;">Publish Wall Post</a> |
            <a href="#" onclick="share(); return false;">Share With Your Friends</a> |
            <a href="#" onclick="graphStreamPublish(); return false;">Publish Stream Using Graph API</a> |
            <a href="#" onclick="fqlQuery(); return false;">FQL Query Example</a>

            <br />
            <textarea id="status" cols="50" rows="5">Write your status here and click 'Status Set Using Legacy Api Call'</textarea>
            <br />
            <a href="#" onclick="setStatus(); return false;">Status Set Using Legacy Api Call</a>
        </div>
    </body>
</html>

Additionally if you use PHP SDK 3.0 or this new way of javascript sdk to authenticate your site you can enable oAuth Migration in the application setting.

Hope it will help you to understand new javascript sdk.

About mahmud ahsan

Founder And Lead Programmer at iThinkdiff.net

, , , ,

222 Responses to New JavaScript SDK & OAuth 2.0 based FBConnect Tutorial

  1. Nuhil July 22, 2011 at 6:37 pm #

    Another nice post. Thank You Mahmud vai :)

  2. venkatesh July 22, 2011 at 8:00 pm #

    hi,
    for desktop app using javascript sdk we need to enter redirect_uri in options of application ?

    • mahmud ahsan July 22, 2011 at 8:28 pm #

      Venkatesh
      You can manually write the redirection code within this code block, but when redirect, provide extra parameter and trace that, otherwise user will fall in redirection loop.

      if (response.authResponse) {
                      //user is already logged in and connected
                      FB.api('/me', function(info) {
                          login(response, info);
                      });
       
                  }
      
      • max November 28, 2011 at 6:11 pm #

        I don’t undertand how I should put it together:
        redirect_uri
        and
        if (response.authResponse) {
        //user is already logged in and connected
        FB.api(‘/me’, function(info) {
        login(response, info);
        });

        }
        If I would like to give my user access to my site (page) where my user is loggedin. How do I do it?

      • larry vu February 17, 2013 at 2:14 pm #

        Source code got nothing …just readme.txt and image file….would you please give me link that can download the source code?

  3. venkatesh July 22, 2011 at 8:01 pm #

    i like ur posts…thanks

  4. Muckinger July 22, 2011 at 9:53 pm #

    Any hint how to use php-sdk 3.0 together with the new js-sdk for login?

  5. Andrei July 23, 2011 at 12:52 am #

    Code does not for me. I see only Login button and nothing else. Button does not work.

    • Varun Kumar April 4, 2014 at 5:12 pm #

      You need to add “website” as Platform for this to be running
      Open your project in FB Console
      Settings -> Add Platform -> Choose website

      In that mention your site url, if its localhost specify as below

      http://localhost:8080/

      • Mubashar May 10, 2014 at 2:33 pm #

        Mr. Kumar i am developing a mobile app using html5 and jquery mobile what platform should i add for that. By adding website it worked perfectly fine. Thank You

  6. Justin July 23, 2011 at 8:38 pm #

    This is a good tutorial but assuming you are doing a mysql store on the users, how can you login by cross-referencing your own database for users already registered to retrieve data you’ve collected?

  7. keith July 23, 2011 at 9:17 pm #

    How do you use an RFID tag to post a places message direct from a server instead of browser>server>login?
    Couple of sites I have seen use this (rfid reader) without a browser but cannot figure out the process
    Any help?

    • mahmud ahsan July 23, 2011 at 9:18 pm #

      Sorry I don’t know what is RFID tag.

  8. nausheen ahmad July 26, 2011 at 3:32 pm #

    hi,
    Permission is required after going to application page but i want to know how i will go to permission pop up directly when accept the application request…but all in javascript.

  9. Vanessa Lim July 27, 2011 at 6:22 am #

    I am implementing the simple FB credits sample BFF app (PHP) for my game but when users clicks the pay now button, the payment box does not appear.

    On the back end it looks like the signed request was not passed through. Is it a problem with the call back page? Should I change REQUEST to POST instead?

    MY CALL BACK PHP SCRIPT

    // parse signed data
    $request = parse_signed_request($_REQUEST['signed_request'], $secret);
     
    
    if ($request == null) {
      echo "nothing";
    }
    
    $payload = $request['credits'];
    
    // retrieve all params passed in
    $func = $_REQUEST['method'];
    $order_id = $payload['order_id'];
    
    if ($func == 'payments_status_update') {
      $status = $payload['status'];
    
      // write your logic here, determine the state you wanna move to
      if ($status == 'placed') {
    	$next_state = 'settled';
    	$data['content']['status'] = $next_state;
      }
      // compose returning data array_change_key_case
      $data['content']['order_id'] = $order_id;
      } else if ($func == 'payments_get_items') {
        // remove escape characters  
        $order_info = stripcslashes($payload['order_info']);
        $item_info = json_decode($order_info, true);
        //Per the credits api documentation, 
        //you should pass in an item reference
        // and then query your internal DB for the proper 
        //information. Then set the item 
        //information here to be returned to facebook 
        //then shown to the user for confirmation.
        if ($item_info == "1a") {
         $item['title'] = 'BFF Locket';
         $item['price'] = 1;
         $item['description']='This is a BFF Locket...';
         $item['image_url']='http://www.facebook.com/images/gifts/21.png';
         $item['product_url']='http://www.facebook.com/images/gifts/21.png';
        }
        //for url fields, if not prefixed by http:,
        //prefix them
        $url_key = array('product_url', 'image_url');  
        foreach ($url_key as $key) {
          if (substr($item[$key], 0, 7) != 'http://') {
            $item[$key] = 'http://'.$item[$key];
          }
        }
        $data['content'] = array($item);
    }
    
      // required by api_fetch_response()
      $data['method'] = $func;
      echo json_encode($data);
    ?&gt;
    
    • Alex June 4, 2013 at 7:14 am #

      I just wanted to extend a thanks for this information. It is extremely unfortunate how little documentation Facebook gives on their own API. Thanks again!

  10. Zeal July 30, 2011 at 10:01 pm #

    I am forever indebted to you for this infomairton.

  11. Gaurab August 2, 2011 at 9:02 am #

    Hi Mahmud,
    Thanks for providing all these great facebook tutorials.

    One question i want to ask you is that, I used one of your graph api App and the problem is that when i look at the “Application Settings” page it shows the access token expire date just after 1 hour.

    So that means i am not able to further test my application, the redirect url simply doesn’t work as the access token is invalid.

    Can you suggest me any workaround for this.

    Thanks

  12. Niko August 2, 2011 at 9:49 am #

    Hey, does this new javascript sdk works with the php sdk v.3.0.1? How can i use the php with this?

  13. monica August 3, 2011 at 6:36 pm #

    Hi, I like the way you have described. Please share the source code link. My question is, can we use the same code to post a wall offline when user is not connected in facebook. Please give your pointer on this. It will be really helpful.

  14. Xahyd August 5, 2011 at 5:40 pm #

    how can i get and save user’s facebook id and access token in db, i m using php but wanna connect using javascript sdk

  15. Vatroslav August 6, 2011 at 2:29 am #

    Hello, I see there are already 3 questions about mutual
    work of new JavaScript SDK with new PHP SDK. I spent
    several hours today trying to make login with XFBML login button and FB.Login methood, but PHP SDK don’t see that
    user is logged.

    Please let as know if you have confirmation that it is possible. I suggest to make a new blog post about it
    with all tips and tricks. Thank you for all your great work.

  16. Peter August 6, 2011 at 8:34 pm #

    Hi,
    very nice tutorial, but it is very strange it is not working even if i use the complete code. I copied the source code from:http://thinkdiff.net/demo/newfbconnect1/jssdkouth2.html and replace the app id with my one.

    so far so good. if i open my new site, i push the login button, but nothing happens. i already added some console output in the js, but not any output. if i am connected the facebook already, the new site recognize this, and show me the logout button. if i press it, logout works, and NOW the login also. if i refresh the page since i am not connected with facebook the login button do not work. have you any hint what the problem is here? Thanks in advance
    Peter

  17. David Bilby August 7, 2011 at 10:25 am #

    I love your stuff, but I’m playing with the idea of using the javascript sdk and php. The problem I’m running into is that I’m not sure how to use the javascript and then create a user row in our database and authenticate with our site. Any help would be appreciated.

  18. Muckinger August 9, 2011 at 1:25 pm #

    I love your tutorials and examples, the best ressource for FB-Development. ThX!
    And as the others mentioned, an Example for JS & PHP-SDK together would be great. The new bug-fixed PHP-SDK is out now (3.1.1), and it should work together with JS-SDK and oAuth.

    • mahmud ahsan August 10, 2011 at 2:24 pm #

      Thanks for your information, if I could manage some time definitely I’ll write a new post.

      • Meeran April 24, 2013 at 6:58 pm #

        Login button not working….. but live demo is worked,pls help me

  19. sanjay August 11, 2011 at 11:33 am #

    Hi! As other people requested can you write a PHP SDK too? and the share pop up doesn’t work in ie8, any ideas?
    Btw, Thanks for the cool info!

  20. Friv August 11, 2011 at 1:14 pm #

    Hi Mahmud,
    Thanks for providing all these great facebook tutorials.

    One question i want to ask you is that, I used one of your graph api App and the problem is that when i look at the “Application Settings” page it shows the access token expire date just after 1 hour.

  21. Y8 August 11, 2011 at 1:15 pm #

    This is a good tutorial but assuming you are doing a mysql store on the users

  22. Y8 August 11, 2011 at 1:16 pm #

    How can i get and save user’s facebook id and access token in db

  23. Y8 August 11, 2011 at 1:19 pm #

    I love your tutorials and examples, the best ressource for FB-Development.

  24. Shiv August 17, 2011 at 3:41 am #

    Hey, I just wanted to say thanks a million for this post. I had a little question though. When used in a page with Disqus comments, it seems that Disqus overwrites my appid. Is there a way to prevent this? Thanks again!

  25. annie August 20, 2011 at 1:27 am #

    For the people who are having trouble getting more than a login button to show up.

    I had the same exact problem. After some debugging in firebug, I found the following:

    * the code looks for (well, not really requires) an animated gif (ajax-loader.gif). I don’t think it’s necessary for the code to work, but it gives you status of loading.
    * more importantly, you should make sure the app id you are using is valid AND your are serving your page from something that matches the URLS you have registered for the app id. Facebook does not seem to be returning the javascript sdk if that is not the case. You can figure out if this is the case for you by running something like firebug and checking to see if you are getting the fb scripts.

  26. Thanh Tung August 21, 2011 at 9:43 am #

    Do i have to install any environments for these app?
    I intend to add apps/ functions help my site viewers can comment on post using Twitter, Google, Facebook, Zing account (without Disquis).

  27. Barış August 22, 2011 at 3:52 am #

    thx mahmud.

  28. J C August 26, 2011 at 3:45 am #

    Thank you Mahmud for the script!

    If anyone is using this with an AJAX site, you might notice that the script only runs once. If you want it to run again, add the following two lines at the start:

    if (window.FB) delete window.FB;
    if (window.fbAsyncInit) delete window.fbAsyncInit;

  29. mistered August 29, 2011 at 8:09 pm #

    Hi,

    Nice post :)

    How can i put a data in a database (this name for exemple) (i want to know if the user is register on my site)

    thx

  30. Tarun September 4, 2011 at 12:54 am #

    How To Publish Feed and Status Update Direct to Pages and Groups ,Any
    Idea.Kindly provide me solution

  31. Ian September 6, 2011 at 9:57 am #

    Hi there. First off, thanks for your tutorials.

    I’ve tried both your invite method and the FB.ui({ method: ‘apprequests’,
    message: ‘Here is a new Requests dialog…’}); method and though I’m getting a list of friends, the requests don’t seem to be reaching them Is there a way for me to debug this?

    Thanks.

    • Ian September 6, 2011 at 10:36 am #

      Egads…guess it would help if I realized that having the app in Sandbox mode means you can’t send request to non-developers. :-)

  32. Velmurugan September 7, 2011 at 6:05 pm #

    Excellent Article … helped me to solve big issue …

    thanks mahmud ahsan

  33. Sandy September 9, 2011 at 4:34 pm #

    Hello Evveryone…I am totally new to FB app development.
    My First app is a simple 3 html page program
    1) A simple html landing page with a button asking the user to go to app. This click opens OAuth popup and registers user…I have used a simple dialog oauth redirect. I am also getting the reponse type as access token.
    2) A simple form with options to select and submit to see the result
    3) Result.htm page showing an image.

    My prob is how to use the access token on page 2 or shud I reload the JS sdk for fb on this page as well, tho I am nt doing anything with it there but I surely need the token on page 3 as I want to tag and upload the image on user’s profile.

    Can anybody help me with it. I would appreciate some steps I need to follow and a piece of code.
    P.S I am trying to to this using javascript..no php no jsp jst simple html and javascript.

  34. Ollie September 12, 2011 at 8:31 pm #

    Awesome post Mahmud!

    My question is whether it is possible to access the user’s friends list (I have read that it is) and then be able to tag friends in the textarea.

    I am working on a project and the ability to do this would be extremely helpful.

    If it is at all possible then could you possibly post the code???

    Many thanks.

  35. Kristoffer September 14, 2011 at 4:12 am #

    Is it just me or is this not working anymore?

  36. cafeasp September 17, 2011 at 12:13 am #

    Very Good! Keep the info coming…

  37. Yinch September 19, 2011 at 1:30 am #

    Thanks Mahmud, for making the steps so much easier!

  38. Grillermo September 25, 2011 at 12:48 am #

    Thanks for this great great tut Mahmud.

  39. Grillermo September 25, 2011 at 12:58 am #

    I got it to work with the code inside tags embeded in the html, i moved the code to a .js file and sourced it from my html and it stopped working. Is this something to do with the FB async calls?

  40. Moumen Rahhali September 27, 2011 at 3:09 am #

    http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/

    Is this Api no longer working after the 1 october ?! Thanks for your answers

  41. Houman September 28, 2011 at 1:15 am #

    Mahmud,

    Thank you for taking the time and posting this. I had a question though: in the facebook authentication process (your part #2 above) is there a way to check and see if the user is connected to my app after checking to see if they are already logged into facebook and then change the button to either login or register based on that?

    The reason for me asking that is that I am also saving the userid and email to my own database after the user connects to my site for the 1st time just in case facebook authentication stops working or they change anything and for any reason my users cannot connect. In that case they would be able to retrieve a temporary password using their email address and still log in to my site using my own log in. I just do not want to check my database every single time a user logs in to see if they have already been added and think it would be better to check the “connected” status and act based on that.

    I already tried the FB.getLoginStatus(function(response) {
    if (response.status === ‘connected’) etc… method but it does not seem to be doing anything?

    • Houman October 19, 2011 at 2:44 am #

      Mahmud,

      Any thoughts on this one?

  42. Cahya September 29, 2011 at 3:44 pm #

    Please help. I’d like to use instead the usual button. How can I tweak the code? Thank you so very much.

  43. Cahya September 29, 2011 at 3:45 pm #

    Ups sorry. seems the tag has been auto stripped. I mean I’d like to use fb:login-button fbml button. Thanks.

  44. Houman September 29, 2011 at 7:45 pm #

    My idea is to use the button also but it seems to not be working with the registration-url attribute if oauth is set to true which I believe is necessary after Oct. 1st?

  45. chetan October 3, 2011 at 4:14 pm #

    hey buddy i tried ur application using Demo Application…. it is awesome but when i copied ur code & tried to execute it….it is not working ….even i replaced ur app id with mine app id…..but not working …it is just giving a button with a msg but when i am clicking it …. it is not redirecting the page to facebook login page ………….

    Steps i followed…….
    opened ur code copied in notepad file and saved in a .html file & tried to run

    hey i am new to java ……pls help me ….. better if u mail me ur mail address and phone no…… it’s urgent……….. pls help me

    • mahmud ahsan October 8, 2011 at 12:52 pm #

      Would you please open firebug in firefox to check any javascript error occurred or not. The code is actually quite simple.

  46. chetan October 4, 2011 at 10:03 am #

    hey dude i waiting for ur reply …. its urgent ….please………

    • Daniel October 7, 2011 at 1:07 pm #

      You can’t just expect him to respond because you have an urgent issue…

      • mahmud ahsan October 8, 2011 at 12:53 pm #

        Thanks Daniel, actually its really tough to answer quickly or check comment every time, as I also do a job.

        • Obafesta October 19, 2011 at 8:30 am #

          The example code doesn’t work.

  47. Kate Juliff October 9, 2011 at 12:57 am #

    Excellent – clearly written – first article I’ve seen on this that really makes sense!

  48. Calado October 10, 2011 at 9:31 pm #

    Hi, how can I select the id and message tags from posts that a user liked?

  49. Juan October 19, 2011 at 11:49 am #

    Thank you for your great articles.

    One question: For using the stream publish button do I need to get authorization from the user or it’s not needed?

    Thank you in advance

    • mahmud ahsan October 19, 2011 at 1:52 pm #

      You need user’s authorization.

  50. roy October 21, 2011 at 2:17 pm #

    Very Nice tutorial, implemented it, tweaked it and YES : it works!!!!

    Question: maybe you can give another post on now what??!!

    Meaning: how can we use this info:

    1) build a database
    2) let the customer know what we know and how they can udate the info ( like for example
    groupon )

    etc. etc.!

    • roy October 21, 2011 at 5:03 pm #

      oeps…..didn’t look for more on your site!
      plenty of totorials!

  51. roy October 21, 2011 at 2:31 pm #

    Question:

    I notice when i try your demo i get 1 request for permission, when i look at my site i get 2 questions for permission??????

    test page: http://www.fotogaaf.nl/test.html

    How can i fix that??

    Screenshots:

    your request for permission : http://www.fotogaaf.nl/facebook/1.png
    my 2 requests for permission: http://www.fotogaaf.nl/facebook/2.png & http://www.fotogaaf.nl/facebook/3.png

    Looking forward to your answer!

    • roy October 29, 2011 at 4:55 pm #

      Can Anybody help me with this issue????

      • harshada November 30, 2011 at 1:57 pm #

        hi roy ,
        I am facing same problem …please reply me if you got solution

  52. Jerry Crick October 29, 2011 at 11:23 pm #

    Hi Mahmud

    Truly a good post – I have been struggling with the PHP sdk et al and this new post using javascript SDK and OAuth 2 seems very good. I suspect we can use PHP SDK in conjunction with Javascript SDK – it wouldn’t make sense if they could not co-exist.

    With respect to your comment in an earlier post about lack of time etc. do you envisage providing a paid for QnA service – I think many of us would be happy to ‘donate’ or pay for answers to our FB / Javascrip / PHP issues.

    Thanks anyway

    Jerry

  53. basit husain October 31, 2011 at 11:34 pm #

    @mahmud ahsan

    This is very urgent.Please i am using this code .my problem is that i have downloaded ur code but the login button is not working . i mean there is no action is generating after clicking the login button ..can u please tell me how to solve it dude.i am using this in my website.but it should be working when i use it simply after downloading it .i have changed the api id still i am not getting what to do .i have a deadline .can u please tell me why your code is not working after downloading it ,…..

    please reply as soon as possible…..

  54. basit husain November 1, 2011 at 12:00 am #

    dude is it important to upload this code to the server where my website is !!!!! i mean to say that if i use this code on the localhost then it will be working or not??? i mean i just copied ur code in the notepad and change it to html file..its not working.i have alos tried with the eclipse the thing is not working ..

    i am thinking like i have to upload ths code on to server to match with the url which i have registered with facebook … m i explaining correct… please do reply reply fast !!!!!

  55. Sara November 2, 2011 at 2:17 pm #

    Hi,

    This post was useful. i tried. no what am trying to do is i want to post on the facebook wall even if am not online on facebook(im logged out of fb). i extended teh permission giving offline access. but now when i refresh the page it gain goes back to login button. how to stop it and post on wall without needing to login again.

    i m very new to FB coding. pls help.

  56. Paul November 3, 2011 at 3:57 pm #

    Hello,

    I am trying for 2 days now to set my application to ask user for permissions. It just won’t work,
    Using your application works, but when I am using my appid after the login interface, it brings me back to my website.. so I suppose it is something wrong with my application. Is there any way you can tell me what settings to have on facebook api page since that was updated meantime and won’t match your screenshot.
    Greatly appreciated!

  57. Deniz November 8, 2011 at 12:06 am #

    Cool. But how can we store u_id and how can we use them? I checked codes but everything is JavaScript. Do we need to use ajax to parse all of them to php for this purpose, or need another method?

    I also read yours PHP SDK 3.0 & Graph API base Facebook Connect Tutorial, but it didn’t work.

    Thank you,

  58. harshada November 30, 2011 at 1:13 pm #

    I notice when i try your demo i get 1 request for permission, when i look at my site i get 2 questions for permission??????

    test page: http://mm.matrixcsi.com

    How can i fix that??

    Screenshots:

    your request for permission : http://www.fotogaaf.nl/facebook/1.png
    my 2 requests for permission like: http://www.fotogaaf.nl/facebook/2.png & http://www.fotogaaf.nl/facebook/3.png

    please reply

  59. avinash December 1, 2011 at 5:20 pm #

    the code which u have given in (http://thinkdiff.net/facebook/new-javascript-sdk-oauth-2-0-based-fbconnect-tutorial/) is working fine in demo. But itz not working when we use the same code in my site i.e., login button is not working fine when we try.

  60. praveen December 2, 2011 at 6:10 pm #

    Hi Mahmud

    Nice post and very much help full,but the above code is working only in html page ,could you please clarify that how to make it work in an aspx page. In aspx page the dialog box is not
    disappearing after giving the login credentials, please help me…

    thanks

    • akansha March 13, 2012 at 6:21 pm #

      how r u doing this in apsx page. Can you please share the code.

    • akansha March 13, 2012 at 6:24 pm #

      how r u doing this in aspx page. Can you please share the code.

  61. avinash.valiveti December 6, 2011 at 6:30 pm #

    The above code is working fine when we are utilising it for demo in the same page. But when we are using the same code in our server LOGIN button is working only 2-3 times then itz not working fine. Can any body help me in resolving this problem.

  62. baggio December 14, 2011 at 10:00 am #

    how to sign in to facebook chat OAuth2.0 based with gloox?

    I used gloox to chat with my facebook buddy, and the authentication mechanisms is X-FACEBOOK-PLATFORM.
    Now I use OAuth1.0 facebook sdk, but facebook will change the sdk to OAuth2.0. and I do not know how to sign in to facebook chat with the access token.

    now my Chat Authentication code before connection as follows:

    client_.setSASLMechanisms( SaslMechFacebook );
    string key(ini.api_key);
    key += “|” + string(password) + “|” + string(ini.secret_key); //password is the session key facebook returned
    client_.setAuthcid( key );

    How to change this code to adapt to the OAuth2.0?

    • Phil March 16, 2012 at 1:31 am #

      did you find out?

      I’m needing to do that right now.

  63. vijay December 18, 2011 at 5:19 pm #

    Thanks bro good job……….

  64. tnoah December 18, 2011 at 11:23 pm #

    You Sir are a gentleman and a scholar! This tutorial was of utmost delight! I actually got my FB code up and running thanks to you!

  65. Irulappan December 19, 2011 at 2:58 pm #

    the html ppage shows only login button. when i click on it it do anything… how to work out pls explain briefly…… Thanks.

  66. Vik December 19, 2011 at 6:35 pm #

    HI..
    this article is awesome..it worked fyn for me …
    But there is a problem like i want to access the user’s info across all the pages in my web site..how can i achieve this in asp.net??

    Waiting for your Reply…

    • Irulappan December 19, 2011 at 6:57 pm #

      HI Vik,

      for me it shows only login button and it does nothing.
      pls help me…….

    • Irulappan December 19, 2011 at 6:58 pm #

      HI Vik,

      pls help me…….

  67. Chandan Kumar December 21, 2011 at 2:56 am #

    Thanks for this helpful post. Could you please tell me how to get facebook userid using your code?

  68. Atif Nazeer December 30, 2011 at 12:59 am #

    If I download your source code and add my application id in jssdkouth2.html and upload it at my site, should this work?
    For me, its not working. Is there any settings required at fb?

  69. omprakash December 30, 2011 at 12:02 pm #

    Superb post! Its working in all browser except Firefox and IE ? It showing some errors in when looking in web developer is showing error like :

    uncaught exception: Error: Permission denied for to get property Proxy.InstallTrigger

    Can you help me to understand why it is coming? please

  70. Shaswat January 2, 2012 at 1:54 pm #

    Hi Mahmud Ahsan :)
    I am new to FB praogramming
    wish u a very happy new year and really very thankful for your great posts all are very nice as well as helpful.

    but i have doubt wen i am logged out from my site then automatically again logged in into my website could u help me here hw can i handle this autologin

  71. tarek January 2, 2012 at 9:13 pm #

    great tutorial
    but i have some problem with XD proxy when the login box opens
    it opens the box and hangs doesn’t complete the process
    any solution for this case?

  72. Amandeep January 4, 2012 at 12:58 pm #

    Hi mahmud,

    Thanks For this post this help me a lot. And this is exactly what i was looking for, i did lots of googling but this is the best article that i found yet on FB integration. Again Thanx a lot…:))

    Amandeep

  73. Vipul Jain January 5, 2012 at 3:04 pm #

    Hi,
    Found your post helpful…I want to integrate Facebook feeds in SharePoint 2010 application.I am referring Facebook Graph javascript SDK. My requirement is that the user is not prompted again and again to login with Facebook credentials. I am able to get the access token through code.

    Any help would be highly appreciable

    —————————-

    Vipul Jain

  74. George January 6, 2012 at 4:49 pm #

    Hi Mahmud and a Happy new year!

    Really cool script… only issue Im having (and appears in your demo too) is the Share with Friends link doesn’t seem to work… any solution?

    Thanks

    george

  75. Carol January 12, 2012 at 5:29 pm #

    Thanks for the great Oauth example! For any one that is unable to get the Login working from localhost or 127.0.0.1, make sure you add it as a site url in the developer facebook apps settings under “website”

  76. praveen February 1, 2012 at 4:41 pm #

    hiii to all
    can any one find the problem in this method ,with this method actually one can post a link on friends wall but it is not working,please help me.
    function share(){
    showLoader(true);
    var share = {
    method: ‘stream.share’,
    u: ‘http://www.mobizill.com’
    };

    FB.ui(share, function(response) {
    showLoader(false);
    console.log(response);
    });
    }

  77. GPUToaster February 1, 2012 at 7:23 pm #

    This is the best tutorial I have found on the internet. Well explained and keep it coming! :)

  78. Sona February 4, 2012 at 4:34 pm #

    I tried it today ..its not working…

  79. Irulappan February 4, 2012 at 6:35 pm #

    Hi Sona,

    Try this code.It working in my project.

    require “facebook.php”;

    define(‘FBApiAppId’,FBApiAppId);
    define(‘FBApiSecret’,FBApiSecret);

    $facebook = new Facebook(array(
    ‘appId’ => FBApiAppId,
    ‘secret’ => FBApiSecret,
    ));

    $user = $facebook->getUser();
    if ($user) {
    try {
    // Proceed knowing you have a logged in user who’s authenticated.
    //$user_profile = $facebook->api(‘/me’);
    $uid = $facebook->getUser();

    $friends = $facebook->api(array(
    “method” => “fql.query”,
    “query” => “SELECT uid,name,pic_small FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())”
    ));

    //echo “”; print_r($friends);exit;
    }
    catch (FacebookApiException $e) {
    //echo ”.htmlspecialchars(print_r($e, true)).”;exit;
    $user = null;
    }
    }

  80. reden87 February 11, 2012 at 10:00 pm #

    Hey guys!

    If you try this tutorial in your server, and when you click the login button but it doesn’t do anything it’s probably because your facebook app in sandbox mode!

    • Danne June 28, 2012 at 10:21 am #

      Aaaah!!! Thank you Reden87!
      I’ve spent 12 hours trying to find out why this doesn’t work.
      Turning off sandbox mode was the simple solution.

  81. saurabh February 13, 2012 at 6:21 pm #

    I am Facing two issues :
    1) When user login, the login pop up appears and Extended permissions steps once user clicks allow it kept open and showing blank pop up
    2) When user clicks on Share With Your Friends, only the loader image kept on showing
    3) Kindly advice how can I extract users friends list
    Reference URL

    http://apps.facebook.com/simply-we

  82. Daniel February 14, 2012 at 7:57 pm #

    Is anyone having problem with safari, ie7 and ie8?

    • Daniel February 14, 2012 at 8:01 pm #

      PS. In my case I am implementing it inside a canvas (Facebook app).

  83. Kanak February 27, 2012 at 2:56 pm #

    Hello,

    Thanks for nice script. I have one issue. This script is working fine with all browser for Windows Xp but it is not working in MAC OS safari browser, firefox and crome browser. I have to reload page 2 times to run the same page in MAC OS…

    Please give me suggession..

    Waiting for your positive reply..

  84. Javi March 1, 2012 at 1:41 am #

    Hi,

    first at all thanks for your work, really useful, but as some people said before, I can make the source code run, and my application is not in sandbox mode as someone suggested, any clue about what is happening?

  85. amr Zaki March 2, 2012 at 2:31 pm #

    Hi mahmud,
    This article is very useful for all programmers according to me,

    But i cant create event out of facebook with javascript sdk.

    How can i create event out of facebook using with Facebook Javascript Sdk?
    Nearly all examples i found not worked.

    • mahmud ahsan March 3, 2012 at 11:02 pm #

      Hi Zaki, I never checked or used event api. So please facebook wiki or their official forum for help.

  86. Tom M March 6, 2012 at 3:30 am #

    Thanks for posting this!!!

  87. aitzol March 16, 2012 at 6:12 am #

    hi, does anyone know how to save user data in a db? Why do I need to pass javascript variables to php, and as I do? Does anyone know of any example? Thanks.

  88. kizi March 17, 2012 at 1:18 pm #

    Thanks for nice script. I have one issue. This script is working fine with all browser for Windows Xp but it is not working in MAC OS safari browser, firefox and crome browser. I have to reload page 2 times to run the same page in MAC OS…

  89. Ali March 19, 2012 at 7:26 pm #

    Share With Your Friends is not working, kindly help

  90. yogesh March 22, 2012 at 6:28 pm #

    i have the same problem can anyone help
    all the codes i have search is in PHP . and i am
    with jsp javascript .
    How do you handle expired Facebook tokens? Facebook tokens expire in ~2 hours. So if the user is logged into the app and then tries to post to Facebook after the token is expired, how do you handle that exception?

  91. navnath April 5, 2012 at 5:01 pm #

    Can we provide hyper link to Caption in stream publish method?

  92. y8 April 13, 2012 at 3:51 pm #

    Thank You

  93. Denis April 18, 2012 at 9:46 pm #

    Mahmud Ahsan, hi.
    Does facebook change something in the javascript sdk api?

    Try yourself, click in your demo Login, after logged in – click Logout.
    after this try to push this button and login again.
    1st: button doesn’t change text to Login
    2nd: firebug says ‘FB.logout() called without an access token.’
    3rd: it doesn’t logged in to facebook again =(

    • Denis April 19, 2012 at 8:47 pm #

      solved! the problem was with FB.event.subscribe. I’m just changed auth.statusChange to another listener – auth.authResponseChange

  94. Subhakar April 19, 2012 at 4:46 pm #

    this source code was downloaded, but not working in my site.
    i can’t identify the problem. tell me what is the reason?

  95. Yatin April 30, 2012 at 6:40 pm #

    Working fine with html page but, when i implement it on aspx page fb return blank and popup not close.

    Any Idea?

  96. Efthimis May 1, 2012 at 4:45 pm #

    Does this code works the same but for mobile version?

    • Denis May 1, 2012 at 4:53 pm #

      dude, are you kidding us? )

      what do you mean on ‘mobile version’?

      facebook has a lot of SDK’s, in this example we use javascript SDK, also they have iOS SDK and Android SDK, look here https://developers.facebook.com/docs/sdks/

  97. whatever May 13, 2012 at 6:00 pm #

    it’s amazing ……..but I want to know how i can hide the button login after I clicked on it

    • Denis May 13, 2012 at 6:17 pm #

      (function(){
      $(‘#your_button_id’).on(‘click’,function(){
      $(this).hide();
      })
      })()

      • whatever May 13, 2012 at 6:24 pm #

        thanks,

        sorry I’m beginner where should I put this code.

  98. Denis May 13, 2012 at 6:41 pm #

    so.. that means you don’t know about jQuery :)
    okay, try this. put this into your html document (preferably at the bottom of page, over )

    var button=document.getElementById(‘fb-auth’);
    button.onclick=hide_button

    function hide_button(){
    button.style.display = ‘none';
    }

    • Denis May 13, 2012 at 6:42 pm #

      over CLOSING body tag. blog cut tags :)

      • whatever May 13, 2012 at 7:01 pm #

        it’s not work

  99. whatever May 13, 2012 at 7:06 pm #

    I use the code below this sentence: Full Source Code of this project. Or direct download from github,and I want to integrate hide button with it.

    • Denis May 13, 2012 at 7:17 pm #

      hey buddy, anyway biggest part from this tutorial doesn’t work too, as you can see comments of another people) you have to fix a lot from topic-starter’s code and then think about your button )

      my advice: try to find a better solution on the web, and.. looks like you began too early to play with facebook api. learn at least javascript first

      • whatever May 13, 2012 at 7:35 pm #

        sorry but that code run with me and post to my wall without any problem

        • Denis May 13, 2012 at 7:40 pm #

          you make me nervous)

          what button you need to hide ?

          • whatever May 13, 2012 at 7:48 pm #

            I’m really sorry,

            in code we have this button:Login
            and I need to hide it after click on it

          • Denis May 13, 2012 at 7:57 pm #

            JavaScript code what i gave to you.. did you wrapped it in script tags?)
            i said, blog cutted the tags

            try this:
            http://jsfiddle.net/eVcEz/

  100. whatever May 13, 2012 at 7:54 pm #

    I’m really sorry,

    in code we have this button:
    Login

  101. Fabio May 15, 2012 at 9:35 pm #

    Hi, I just want to ask a single question: I’m going to develop a website for a contest with the Facebook Connect integration, to collect data from users and publish some posts on the users timeline.

    Do I need to buy an SSL certificate to let websites use the FB connect function and use the Graph API and so on, obviously requiring all the necessary permissions when implementing the login?

    The SSL certificate is necessary only when building app inside Facebook (app.facebook.com/whateveryouwant) or not?

  102. whatever May 16, 2012 at 1:13 pm #

    i want to ask how i can do it like yahoo when somebody clicked on the post and doesn’t have permission, the app show to him authorize dialog and after he accept the permission he can see the article

  103. devil man May 17, 2012 at 8:00 pm #

    I want to ask question :
    How can I make this code post to my way one-time only to the similar url.
    and thanks for all.

    • devil man May 17, 2012 at 8:01 pm #

      sorry to my wall not to my way

  104. Lorenzo May 23, 2012 at 5:23 am #

    HI or Ciao

    I’m testing an app using or

    Client-side Authentication,

    or your OAuth 2.0 based FBConnect tutorial

    scope: email,status_update,publish_stream,user_about_me,user_checkins

    everything works I can publish_stream if the user accept the app scopes
    in two ways one at the first login and one each time he use the app
    (just a test)

    The problem is that I’m getting crazy because, when user accept the email permission,
    I’m not able to catch where emails are stored

    I hope you’ll can give me an help

    thanks

    Lorenzo

  105. chaotic May 23, 2012 at 5:52 am #

    hi,
    thanks for the post.
    how can I store the data I get through my app on facebook? (for example, birthday, uid etc.)

  106. LittleBoy May 23, 2012 at 6:23 pm #

    HI, i have downloaded the same page and its not working for me. is there anythig to be modified to execute jssdkouth2.html.

    please help me out to test this sample

  107. Srinivas May 28, 2012 at 8:54 pm #

    Hello,

    Very informative tutorial and appreciate such a detailed step by step explanation.

    However, how do you ensure the pop-up login window is centered on the screen in Firefox. Right now this window is to the right of the screen

    Thank you in advance

    Srini

  108. Prasanth June 5, 2012 at 5:05 pm #

    Hi mahmud ahsan, its very simple and easy to understand. Appreciate your great effort!. It would be better if i get an article same like this for Google connect.

    • Prasanth June 5, 2012 at 5:06 pm #

      using Javascript

  109. Anshuman June 7, 2012 at 11:54 am #

    Hi,

    Thanks for the stuff !

  110. Matt June 11, 2012 at 11:24 am #

    Hello! I am looking for a solution to do my facebook app, can identify differents facebook pages where it could be contained.

    I am using just javascript.
    Signed_Request seems be the option, but I don´t know how can parse it with js.

    Do you know any method or property wich allows a facebook app, know the id of the page wich contains the canvas?

    Thank you so much for your help!
    Best regards! Matt.-

  111. srikanth June 18, 2012 at 10:51 am #

    hi can anyone help me …
    How to add a search box of facebook in my website that search for all the comments or post of particular topic or about a person ….

    Example: If i type a word like “apj abdul kalam” it has to retrieve all the comments about abdulk kalam and display on my webpage ..

    please help me its very urgent for me…….thanks in advance….

  112. srikanth June 18, 2012 at 10:53 am #

    by using javascript and html5 i am trying to develop this appliction. please help me

  113. Mohamed Asif June 19, 2012 at 4:49 pm #

    Hi Mahmud, nice post, could you please guide me FBCONNECT in PHP.. I need it..

  114. faheem June 23, 2012 at 11:52 am #

    hey i am trying to execute this piece of code. at first it execute successfully but now its stuck. i searched lot about the error but can’t find any suitable solution . you are my last hope, actually i am trying to make authentication from facebook to embed in a website, you used login button to if user not login. i want to make a lil difference i want the code to directly move the user if he/she is not logging and show him/her the login page without clicking .

    response is “Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the Application configuration. It must match one of the Connect or Canvas URLs or domain must be the same as or a subdomain of one of the Application's base domains.”

    please ..

  115. Lijesh June 28, 2012 at 11:56 pm #

    Great Job….. Helpful….

  116. Samuel MacLachlan July 15, 2012 at 2:07 pm #

    Hi, just wanted to say thank you so much for this code! I spent a few hours trying to get this working- then I found this website with your tutorial.
    You are a life saver! :)

  117. Paul July 20, 2012 at 4:08 am #

    Thanks this script works brilliantly! Only issue I have is “showStream()” function does not show up on mobile devices i.e iPad or iPhone. The loader just goes on indefinitely.

    Have your found a solution for this?

    Thanks in advance!

    P.S. You are in Malaysia now? I lived in KL for 6 months. I love SE Asia :)

    • mahmud ahsan July 22, 2012 at 8:40 pm #

      I no longer work on facebook app development. So Please check facebook documentation. Yeah I live in Melaka.

  118. Bahous amal July 22, 2012 at 9:39 pm #

    hi tks for this tutorial….But actually i need to have the ad form of facebook on my website that i’m developping with zend, so is there a way to have that form?

  119. dangtrinhnt July 29, 2012 at 3:34 pm #

    Sorry Mahmud, but the source code I downloaded from the above link doesn’t work on my browser (both chrom and Firefox).

  120. dangtrinhnt July 29, 2012 at 10:11 pm #

    I found my problem. I forgot the App API part!

  121. Muhammad Maaz July 31, 2012 at 5:42 am #

    Can I have the list of my subscribers using this api ? Do twitter provide api similar to this? Do you have any tutorial how to write an facebook app ? Kindly do tell me. Regard

  122. madosx July 31, 2012 at 11:27 pm #

    Great tutorial. But i don’t unterstand why there is nothing fired when i press the login button.

    • Vani S. Hemmige August 1, 2012 at 12:11 pm #

      Thanks for the great tutorial. As mentioned in one of the replies above, if you are running the code on localhost, then in the app settings page, under the section “Select how your app integrates with Facebook”, click on “Website with Facebook Login” and set the site url to http://localhost:port_number and it will work.

  123. mamata August 2, 2012 at 10:42 am #

    Hi from where do i get/download javascript sdk?

  124. sabrina yasmin August 9, 2012 at 2:45 pm #

    ’m sure you’ll create lots of successful projects on paper and hopefully you’ll have some fun as well
    Great tips, thanks for sharing.

  125. Zuhair Taha August 10, 2012 at 5:30 am #

    hello,
    how can I get user email to the member?

  126. Suma August 12, 2012 at 12:12 pm #

    Hi, some times //connect.facebook.net/en_US/all.js doesnot load , im using img for fb connect and fb logout somethimes img does not show ,again if i refresh img appear,

    FB.logout(function(response) {
    console.log(response.status);
    logout(response);

    });

    is not working for IE , but working in Firefox and Chrome Plz help

  127. Sun Ehsun August 17, 2012 at 3:27 pm #

    Thanks

  128. rami August 18, 2012 at 11:39 am #

    hi thanks
    at the top you draw a good workflow
    the code don’t flow it
    1. the line no from the user authorized you site are not implement
    2. the FB.Event are not draw

  129. Robert Jones August 21, 2012 at 2:02 pm #

    Thanks. Very helpful.

    Does anyone know how to get user_address and user_mobile_phone?

    I can only find this but not an update and whenever I query FB with these field requests it “hangs”
    https://developers.facebook.com/blog/post/2011/01/14/platform-updates–new-user-object-fields–edge-remove-event-and-more/

  130. Usman August 27, 2012 at 12:58 am #

    I just downloaded the script and run it on my machine,but it is not running,Do you know what could be the reason?

  131. Subhashi Jayasekara August 27, 2012 at 2:40 pm #

    This is working well. cooooooooooooool.. thanks a looooooooooooooooooooooooooooooot :) :) :)

  132. Ehsun August 28, 2012 at 9:28 am #

    Hi,
    Thanks. But I have a problem. We need to log all the logins! So I send an Ajax request in your login function in order to log it. But I don’t know why the login function is called 2 times! and it ends up in a duplication in our logs!

  133. nav September 1, 2012 at 9:55 pm #

    thanks for the g8 post …but i do have a problem …I have avg installed in my system and it blocks all analytics including //connect.facebook.net/en_US/all.js so clicking on the login button doesn’t work…plz post a workaround it

  134. sunil September 10, 2012 at 6:04 pm #

    Hello, I am trying to run the demo of your application on safari but facebook authentication pop up is not coming up. When i run the demo on google chrome or firefox i see the facebook authentication pop up. Please help.

  135. Ashum September 12, 2012 at 5:01 pm #

    Mahmud Ahsan,

    Thank You for you brilliant tutorial. Thanks also for putting time aside into educating others out there. Its very kind of you. Keep it up!

  136. iie@gmial.com September 24, 2012 at 5:32 pm #

    hey guys check this out
    http://learnwebscripts.com/how-to-login-into-facebook-account-using-php
    its very easy to integrate

  137. Mike N September 27, 2012 at 3:06 am #

    Has anyone tried using this code within an ASP page? If I simply add a form opening and closing tag to the page, the functionality breaks. Am I missing something simple?

    • Mike N September 27, 2012 at 3:07 am #

      Correction, ASPX page.

  138. nothingelsematterz November 3, 2012 at 10:19 am #

    Though it seams like the questions are not replied sometimes..

    But still I have a question I am putting forward..

    This method, even the demo doesn’t work on a symbian phone, can you please make it happen, or if possible .. put forward a new tutorial..

  139. Indocalido November 7, 2012 at 1:45 am #

    If the login button doesnt work, the other possible situation could be that probably you dont have access to the facebook javascript all.js. Try to download it and work with it locally. And thanks man for the post. Its a great help!!

  140. Aaron November 20, 2012 at 4:28 pm #

    This has been the best script I’ve seen out there for working with the FB SDK! Great job!!!

  141. simplemuri November 25, 2012 at 4:19 am #

    Hi all, for those having problems with the login button that isn’t working try this:

    In the line of code:

    remove the “:none”

    that should fix the problem…unless that worked for me ;-)

    Nice tutorial! thanks to the author

    bye

    • simplemuri November 25, 2012 at 4:22 am #

      sorry…where it says “in the line of code:” goes: ”

      • simplemuri November 25, 2012 at 4:24 am #

        This thing is cutting my comments arrggg

        i mean div id=”loader” style=”display:none”

  142. bigusfickes December 16, 2012 at 1:48 am #

    Good show sir. Thank you for making this post and posting the source code.

  143. Jagadesh January 7, 2013 at 5:24 pm #

    Hi, i have tried your code in implementing it for phonegap, but i was not able to do anything.

    could you help me on this issue.

  144. Jagadesh January 7, 2013 at 6:58 pm #

    Hi,

    Can you provide us if you have used any .js files or any .js urls for implementing this,
    I have tried your same code to integrate the facebook, i have changed the app_id of mine but it seems like nothing is working it is not entering into this

    window.fbAsyncInit
    method. Could you me in this issue.
    thanks in advance

  145. http://tinyurl.com/xtrasale09843 February 6, 2013 at 12:13 am #

    Regards for writing “New JavaScript SDK & OAuth 2.0 based FBConnect Tutorial | Thinkdiff.
    net”. I actuallymay undoubtedly end up being returning for more browsing and commenting
    soon. Many thanks, Jayme

  146. shru March 4, 2013 at 3:26 pm #

    Hello,
    Login button is not working. Please let me know the solution. If i remove display none of loader image. Image is getting displayed but when clicked on Login Button nothing is working. Please someone help.

  147. matze March 11, 2013 at 11:05 am #

    sorry to translate for my englich, I’m from Germany and use google

    I would like to use your script but how do I get name, email id and individually interrogated for a form so that daa form is automatically populated?

    such a form cell:

    eingestellt von:

  148. matze March 11, 2013 at 11:09 am #

    such a form cell:

    eingestellt von:

  149. Myron April 6, 2013 at 4:26 pm #

    Along with these two ingredients, comes swallowing your ego and be willing to do work for
    free at first. A working spouse, a loan, a second job and a second supplier
    are all critical items. I enjoyed creative things, and came across
    the idea of starting a gift basket business.

  150. cliknfind April 20, 2013 at 10:52 am #

    nice post ….thanks :)

  151. dot April 22, 2013 at 12:21 am #

    Hi,

    Do u know what code to add in to display a person’s news feed. Like what the get on their home when they log on to facebook desktop site?

  152. Meeran April 24, 2013 at 6:47 pm #

    clicked on Login Button nothing is working. Please someone help.

  153. rakesh April 30, 2013 at 11:21 am #

    bfjhjksadffsdfsdfdsfsfsdfdsdsds

  154. ac repair leads May 27, 2013 at 7:21 am #

    Integrated building systems hvac leadss provided specialized low-voltage services to wire homes, buildings, bridges, roads and the
    rest.

  155. Y8 Dress Up June 19, 2013 at 1:35 am #

    Amazing! Its genuinely remarkable article, I have got much clear idea on
    the topic of from this article.

  156. Y8 Free Car Games June 19, 2013 at 6:21 am #

    Hello! This is my first visit to your blog! We are a team of volunteers and starting
    a new initiative in a community in the same niche.
    Your blog provided us beneficial information to work on.
    You have done a outstanding job!

  157. trenzig June 21, 2013 at 4:16 pm #

    Using windows 7… extract the files to c:\inetpub\wwwrot\FaceBookviaJavascript

    jssdlouth2.html
    line 65 reads e.src = document.location.protocol
    + ‘//connect.facebook.net/en_US/all.js';

    I changed it to e.src = ‘https://connect.facebook.net/en_US/all.js'; …removing the ‘document.location.protocol’
    I was using notepad ++ and when you use the ‘Launch in chrome’ facility you will get file:///C:/inetpub/wwwroot/FaceBookviaJavascript/jssdkouth2.html in the address bar.
    Change this to http://localhost/FaceBookviaJavascript/jssdkouth2.html and it will work fine

  158. kingletit June 24, 2013 at 11:13 pm #

    Superb tutorial !!! I was finding the Facebook docs to be so obscure and fragmented as to be almost impossible to follow and it was really good to see an example of how it all strung together..

    Unfortunately, whilst still trying it out, FB sent me a Developer Alert to say it doesn’t comply with July 2013 Breaking Changes.

    It goes on: ” … is currently using the following deprecated features:
    The publish_checkins extended permission.”

    You didn’t mention the APP-(APPNAME)-PERMISSIONs settings, where I now see there is an extended permissions setting (which I left blank).

    In the July 2013 Developer Roadmap it says:-
    — “Removing ‘publish_checkins’ permissions
    — Publishing a Checkin object is deprecated in favor of creating an Open Graph story
    — with a location attached. You can also create a Post with a location attached using
    — the ‘publish_steam’ extended permission.”

    This looks like a significant change to the code(?) My trouble is, I can’t see any mention of permissions in the tutorial code. What changes are required?

  159. ehijon June 28, 2013 at 11:23 pm #

    Thanks you very much!

    Just a little question: I would like to know if the user is logged at the first load in the php page. How can I do?
    i understund how to publish suff on own user profile page (using these methods), but I don’t know how to get the login info and passed them to some php variables.
    do you know what i mean?

    thank you anyway! :)
    ciao

  160. Anastasia July 5, 2013 at 2:34 pm #

    Magnificent tutorial.

    Very good quality coding!

    Thank you very much.

  161. Jacklyn July 14, 2013 at 4:50 pm #

    A while back when NYC was getting ready to start posting nutrition information in fast food restaurants and are not healthy.
    To get further info on the benefits of a diet being successful.
    The tomato-based sauces tend to have fewer calories in them than food does, consuming fewer calories than
    you are burning off, should work out and the person therefore lose weight.

  162. Bohdan Stupak July 18, 2013 at 3:21 pm #

    Great tutorial. It helped me a lot after day of struggling.
    Good luck and thank you very much!

  163. Ruggero Rossi July 25, 2013 at 3:46 pm #

    I had the problem to authenticate php-side the user after a successfull login with JavaScript SDK.
    I solved it performing an Ajax call passing user email as a parameter after facebook login process.

    Here an example using prototype to perform ajax call

    // misses fb sdk setup etc

    window.fbAsyncInit = function() {
    FB.init({
    appId : App ID
    channelUrl : Channel File
    status : true, // check login status
    cookie : true, // enable cookies to allow the server to access the session
    xfbml : true // parse XFBML
    });

    FB.Event.subscribe(‘auth.authResponseChange’, function(response) {
    if (response.status === ‘connected’) {
    doLogin();
    }
    });
    };

    function doLogin() {
    FB.api(‘/me’, function(response) {
    new Ajax.Request(“/fblogin”, {parameters: {email: response.email, forward: ‘/e-zine’},
    onComplete:function(re){
    // Do whatever you want
    var obj = re.responseJSON;
    if(obj.error == “”){
    if(obj.forward != “”){
    window.location.href = obj.forward;
    } else {
    window.location.reload(true);
    }
    }
    }})
    });
    }

  164. Karthi July 26, 2013 at 5:51 pm #

    Can i post/share image from my web browser to facebook native app (mobile app)…?

  165. Y8 Games August 10, 2013 at 9:07 pm #

    Thanks for the good writeup. It actually was a entertainment account it.
    Glance advanced to far added agreeable from you! By the way, how can we communicate?

  166. Navdeep Sharma August 19, 2013 at 4:35 pm #

    Can i make it work on localhost? Initialization doesn’t work on localhost. Any insights regarding that.

  167. yaswanth August 19, 2013 at 6:39 pm #

    can i run this application on localhost pls give me reply

  168. Mckenzie September 28, 2013 at 11:58 pm #

    I like what you guys are usually up too. This ttpe of ckever work and reporting!
    Keepp up the terrific works guys I’ve added you guys to my personal blogroll.

  169. ngockonvang October 13, 2013 at 12:53 pm #

    Thanks for the good writeup. It actually was a entertainment account it.
    Glance advanced to far added agreeable from you! By the way, how can we communicate?

  170. ngockonvang October 14, 2013 at 3:10 pm #

    Thanks for the good writeup. It actually was a entertainment account it.
    Glance advanced to far added agreeable from you! By the way,

  171. Nduh December 17, 2013 at 6:53 pm #

    your example is no longer working due to this error
    Failed to load resource (file://connect.facebook.net/en_US/all.js)

    please help

  172. Nduh December 17, 2013 at 7:33 pm #

    i’ve fixed it:

    ” // Load the SDK asynchronously
    (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);
    }());

  173. Robin January 6, 2014 at 1:18 pm #

    It not work now :(
    error shown in console tab:
    GET http://connect.facebook.net/en_US/all.js
    (anonymous function)
    (anonymous function)

  174. Rajesh February 13, 2014 at 12:24 pm #

    Thanks for your post…..
    if i am already connected to fb, bt not authorized to app it opens popup 2 times…
    i used the same code what is in demo app of ur’s with my app code….
    any solution?

  175. dani April 15, 2014 at 10:54 am #

    i’ll try your demo project but when i change the appId, login not work? why? and can you explain please ?thx before

  176. Kiran June 10, 2014 at 5:40 pm #

    Excellent article with good sample code.