Graph api & javascript base Facebook Connect tutorial

Posted by mahmud ahsan on May 1, 2010 in FB Connect, Facebook | 145 Comments

facebook-social Some days ago facebook released their new graph api system to develop social sites more easily. Its really cool and I personally like the facebook’s new graph api system.  Facebook also updated their old facebook connect system and provided better way to integrate facebook connect feature, user authentication and calling facebook api from website.

In this article, I’ll highlight javascript base

  1. Facebook connect authentication for websites
  2. How to use graph api
  3. How to show stream publish prompt and share prompt
  4. How to run FQL query using javascript
  5. How to set status using old legacy api calling by javascript

Here is the demo  http://thinkdiff.net/demo/newfbconnect1/newconnect.php

fbconnect-demo

1. Facebook connect authentication

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.

        <div id="fb-root"></div>
        <script type="text/javascript">
            window.fbAsyncInit = function() {
                FB.init({appId: 'xxxxxxxxxxxxxx', status: true, cookie: true, xfbml: true});
            };
            (function() {
                var e = document.createElement('script');
                e.type = 'text/javascript';
                e.src = document.location.protocol +
                    '//connect.facebook.net/en_US/all.js';
                e.async = true;
                document.getElementById('fb-root').appendChild(e);
            }());

Just put this code in your html file after the body tag. This is the most efficient way to load the javascript SDK in your 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="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">

Now we will use another method FB.Event.subscribe so that we can subscribe some events like login, logout, sessionChange.  So modify the window.fbAsynInit and update by below code

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

                /* All the events registered */
                FB.Event.subscribe('auth.login', function(response) {
                    // do something with response
                    login();
                });
                FB.Event.subscribe('auth.logout', function(response) {
                    // do something with response
                    logout();
                });

                FB.getLoginStatus(function(response) {
                    if (response.session) {
                        // logged in and connected user, someone you know
                        login();
                    }
                });
            };

So when user will login first time (not automatically)  login() method will call. When user will click logout , logout() method will call. So define these functions for your application purpose. We also use another method FB.getLoginStatus() within window.fbAsyncInit() function so that when we found user is logged in or connected we will show some info to user.

Now we have to render fb connect button so that user can login or logout.

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

If you don’t need any extended permissions from user then remove perms=”email,user_birthday,status_update,publish_stream” this line. If you don’t want to use standard fbconnect button for login and logout you can define your own connect button. Checkout FB.login for login javascript method and FB.logout for logout javascript method.

2. How to use graph api

To fully understand graph api visit the link . Now i’ll show how you can use graph api using javascript sdk. There is a method FB.api . This method directly hooks graph api and returns result. Sample code

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

By calling this method it will show logged in user name.
In my demo you’ll see another customized method graphStreamPublish(). This method uses FB.api() and does a HTTP POST request to http://graph.facebook.com/me/feed url with message parameter. So that the message will publish to users own wall.

function graphStreamPublish(){
       var body = 'Reading New Graph api & Javascript Base FBConnect Tutorial';
        FB.api('/me/feed', 'post', { message: body }, function(response) {
            if (!response || response.error) {
                 alert('Error occured');
            } else {
                 alert('Post ID: ' + response.id);
            }
       });
 }

3. 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. Checkout streamPublish() and share() methods defination in my demo’s source code .

4. How to run FQL query using javascript

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(){
                FB.api('/me', function(response) {
                     var query = FB.Data.query('select name, hometown_location, sex, pic_square from user where uid={0}', response.id);
                     query.wait(function(rows) {

                       document.getElementById('name').innerHTML =
                         'Your name: ' + rows[0].name + "<br />" +
                         '<img src="' + rows[0].pic_square + '" alt="" />' + "<br />";
                     });
                });
            }

This method used the sdk method FB.Data.query to run FQL. Checkout the link for a complex query example.

5. How to set status using old legacy api calling by javascript

You can still call 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(){
                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');
                    }
                  }
                );
            }

But remember to run successfully the demo, update status and publish stream using graph api you must approved all exteneded permissions those will show you during first access to the application.

Hope this article will help you to make facebook connected social site.

Here is my demo’s full source code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>New Graph api & Javascript Base FBConnect Tutorial | Thinkdiff.net</title>
    </head>
    <body>
        <div id="fb-root"></div>
        <script type="text/javascript">
            window.fbAsyncInit = function() {
                FB.init({appId: '113700398662301', status: true, cookie: true, xfbml: true});

                /* All the events registered */
                FB.Event.subscribe('auth.login', function(response) {
                    // do something with response
                    login();
                });
                FB.Event.subscribe('auth.logout', function(response) {
                    // do something with response
                    logout();
                });

                FB.getLoginStatus(function(response) {
                    if (response.session) {
                        // logged in and connected user, someone you know
                        login();
                    }
                });
            };
            (function() {
                var e = document.createElement('script');
                e.type = 'text/javascript';
                e.src = document.location.protocol +
                    '//connect.facebook.net/en_US/all.js';
                e.async = true;
                document.getElementById('fb-root').appendChild(e);
            }());

            function login(){
                FB.api('/me', function(response) {
                    document.getElementById('login').style.display = "block";
                    document.getElementById('login').innerHTML = response.name + " succsessfully logged in!";
                });
            }
            function logout(){
                document.getElementById('login').style.display = "none";
            }

            //stream publish method
            function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
                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) {

                });

            }
            function showStream(){
                FB.api('/me', function(response) {
                    //console.log(response.id);
                    streamPublish(response.name, 'Thinkdiff.net contains geeky stuff', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
                });
            }

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

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

            function graphStreamPublish(){
                var body = 'Reading New Graph api & Javascript Base FBConnect Tutorial';
                FB.api('/me/feed', 'post', { message: body }, function(response) {
                    if (!response || response.error) {
                        alert('Error occured');
                    } else {
                        alert('Post ID: ' + response.id);
                    }
                });
            }

            function fqlQuery(){
                FB.api('/me', function(response) {
                     var query = FB.Data.query('select name, hometown_location, sex, pic_square from user where uid={0}', response.id);
                     query.wait(function(rows) {

                       document.getElementById('name').innerHTML =
                         'Your name: ' + rows[0].name + "<br />" +
                         '<img src="' + rows[0].pic_square + '" alt="" />' + "<br />";
                     });
                });
            }

            function setStatus(){
                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');
                    }
                  }
                );
            }
        </script>

        <h3>New Graph api & Javascript Base FBConnect Tutorial | Thinkdiff.net</h3>
        <p><fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button></p>

        <p>
            <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>
        </p>

        <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>

        <br /><br /><br />
        <div id="login" style ="display:none"></div>
        <div id="name"></div>

    </body>
</html>

:)

Related Posts

If you think this article kicked ass, subscribe to the RSS feed or follow me on Twitter! Share with your friends, or leave a comment below (or better still, do both!)

Comments (145)

 

  1. maSnun says:

    After setting the status, it alert()s the total response instead of the response ID :)

  2. mahmud ahsan says:

    @maSnun, yeah I fixed it. It would be response.id
    Thank You.

  3. sertac says:

    very successful code thanks for sharing with us

  4. Ghido says:

    Great post! Will you also write a tutorial for using the new Graph API with PHP?

  5. mahmud ahsan says:

    @Ghido, yeah today I’ll write, I am currently testing my code. :)

  6. ccarrasco says:

    thanks for the excelent code and share :)
    from chile :D

  7. Ghido says:

    @mahmud ahsan
    Great! You are the best! :D

  8. James says:

    Yes! PHP would be amazing if you could do a tutorial on that. Can I donate?

  9. Donavan says:

    This is a great intro to facebook api

  10. Chuck says:

    Thank you so much for this tutorial, it’s great. Quick question: I used the graphStreamPublish() to publish content to users wall. But it just publishes text. I would like to add stuff like a URL, a title and an image. How can I do that ? I guess there are additional parameters but I can’t seem to find them

    Thanks

  11. mahmud ahsan says:

    @Chuck, I think the solution would be

    using this link
    http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29

    var attachment = { 'name': 'i\'m bursting with joy', 'href': ' http://bit.ly/187gO1', 'caption': '{*actor*} rated the lolcat 5 stars', 'description': 'a funny looking cat', 'properties': { 'category': { 'text': 'humor', 'href': 'http://bit.ly/KYbaN'}, 'ratings': '5 stars' }, 'media': [{ 'type': 'image', 'src': 'http://icanhascheezburger.files.wordpress.com/2009/03/funny-pictures-your-cat-is-bursting-with-joy1.jpg', 'href': 'http://bit.ly/187gO1'}] }; 
    
    FB.api('/me/feed', 'post', { message: body, attachment: attachment}, function(response)
    

    {message: body, attachment: attachment} I think like this way it will work.
    Let us know if it works or not.

  12. Mike says:

    Thanks this is exactly what i was looking for !!!!!

  13. mixnovich says:

    hi mahmud ahsan am trying to query friends location from facebook please any idea …… i can connect to facebook but the query of friends location is not working out i tried using the idea from your open source facebook album it not working am using php

    thanks for your anticipated response

  14. mahmud ahsan says:

    @mixnovich, i think in new policy your user has to approve friends_location extended permission. Have a look http://developers.facebook.com/docs/authentication/permissions
    So until your facebook user doesn’t approve this permission you couldn’t retrieve location of his friends.

  15. mixnovich says:

    thanks Mahmud ,

    how can i get the user permission actually
    my assignment is to get friends location using it to query flicker using the geo taging from the flicker queried picture place it on google map

    i have done the last two aspect getting pictures from flicker and placing it on google map

    but i have big problem with facebook

    how can i get the user to grant me that permission and also is there any special method to query out the user
    apart from the started examples of your open source facebook album

    Thanks for you anticipated response

    regards
    Mixnovich

  16. mahmud ahsan says:

    @mixnovich, use

    <fb:login-button  autologoutlink="true" perms="friends_location,user_location"></fb:login-button>
    

    if user allows the permission then you can do fql query as usual to retrieve these information.

  17. mixnovich says:

    thanks mahmud

    here is the link to my task

    isaac.comlu.com/

    it showing the facebook login it authenticating but it not reconnecting back to my website for updated info

    here is the link to my source code link :

    isaac.comlu.com/testin–link.zip

    i really need your help and advice

    much respect
    mixnovich

  18. Jk_ says:

    Hi mahmud,

    Have you successfully achieved a graphStreamPublish() with an attachment other than text (like images, videos, …) ?

    This documentation seems uncomplete : http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29

    Cheers,

  19. Jk_ says:

    I forgot to mention that so far it’s the best tutorial I had the chance to read about the new Graph API.

    Thank you so much for sharing.

    Jk_

  20. mahmud ahsan says:

    @mixnovich, your source code link is broken. And your question “it showing the facebook login it authenticating but it not reconnecting back to my website for updated info ” is not clear. after login you can redirect your user to any page and using php or javascript sdk you can get his information. Then what’s the problem ?

  21. mixnovich says:

    am sorry for the broken link stuff . hosting problem

    here is a new link :http://www.4shared.com/file/QEzth22D/myproject.html

    a.the problem is still with the query i guess am not doing it correctly it suppose to get the user location to query flickr but it not working

    Best Regards
    mixnovich

  22. mahmud ahsan says:

    @mixnovich, I found some problems in your facebook related code. First you’re still using old php sdk. Visit http://thinkdiff.net/facebook/php-sdk-graph-api-base-facebook-connect-tutorial/ and learn how to use latest php sdk.

    This is wrong in new php sdk

    $facebook     =   new Facebook($appapikey, $appsecret);
    $user         =   $facebook->api_client->user;
    $session      =   $facebook->api_client->session_key;
    

    2nd, this fql query is wrong

    $query1    =  "SELECT friends_location, user_location FROM user  WHERE owner in ($friends)";
    

    Here http://developers.facebook.com/docs/reference/fql/user you’ll see the user table definitions.

    The query would be

    $query1    =  "SELECT hometown_location FROM user  WHERE uid in ($friends)";
    

    If your user approve the extended permissions I mentioned earlier then this query will return their friends location. Before writing any FQL query never forget to see the FQL table definitions.

  23. mixnovich says:

    Thanks mahmud .

  24. mixnovich says:

    Thanks mahmud .
    i am making the correction right away

  25. Great tutorial, i was struggling with facebook connect after they changed it all again and i really did not know, this post has turned out to be really useful for me to get started with the new sdk and graph api. Thanks brother.

  26. mixnovic says:

    mahmud

    am getting to understand the graph api but there is still a problem for me

    am trying to use the java script fql to query
    here is d code

      function fqlQuery(){
          FB.api('/me/friends', function(response) {
    	 var query1 = FB.Data.query('SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = {0})',response.id);
    
    	var frendsloc=FB.Data.query('select howmetown_location  from user where uid ={0}',query1);
            frendsloc.wait(function(rows) {
             document.getElementById('hometown_location').innerHTML =
               'Location: ' + rows[0].hometown_location + "" ;
           });
        });
    }
    

    please help me check it out

    best regards
    Isaac
    thanks

  27. mahmud ahsan says:

    @mixnovic,
    hmm I found the problem. Actually in fql query http://developers.facebook.com/docs/reference/fql/user you can only get user’s hometown_location data. And for this the extended permissions are user_hometown,friends_hometown not friends_location,user_location.

    Checkout the demo: http://thinkdiff.net/demo/newfbconnect1/friends.php
    first logout and then relogin and give the required permissions.

    <fb:login-button autologoutlink="true" perms="user_hometown,friends_hometown"></fb:login-button>
    

    and the function is

    function friendsLocation(){
       FB.api('/me', function(response) {
            var query = FB.Data.query('select name, hometown_location, sex, pic_square from user where uid IN (SELECT uid2 FROM friend WHERE uid1={0})', response.id);
            query.wait(function(rows) {
                  var data = "";
                  for (var i = 0; i < rows.length; ++i){
                        data += rows[i].name;
                        if (rows[i].hometown_location)
                            data += " => " + rows[i].hometown_location.name + "<br />";
                        data += "<br />";
                  }
                  document.getElementById('location').innerHTML = data;
             });
        });
     }
    
  28. mixnovic says:

    Mahmud thanks ………….you ROCK!!!!!!!

  29. Chuck says:

    Hey Mahmud,

    thanks for your help. I tried your solution but the message is posted but still just the text, none of the attachements are posted

    I tried everything but can’t manage to post something else than text.

    If you could take a look it would help me a lot.

    Thanks a million

  30. Jk says:

    Hi check,

    I did manage to get it works.

    Check the fonction saySomething() on this page:

    http://www.thelbc.be/test/fb/myfunction.js

    Hope it helps

    Jk

  31. mahmud ahsan says:

    @JK, thanks for your nice solution. I’m sharing your code part with others.

    code written by Jk

    function saySomething(myMessage)
    {
     FB.ui(
       {
         method: 'stream.publish',
         message: 'Yeah it\'s my message',
    	 attachment: {
           name: 'Connect',
           caption: 'The Facebook Connect JavaScript SDK',
           description: (
             'A small JavaScript library that allows you to harness ' +
             'the power of Facebook, bringing the user\'s identity, ' +
             'social graph and distribution power to your site.'
           ),
           href: 'http://github.com/facebook/connect-js',
           media: [{ 'type': 'image', 'src': 'http://icanhascheezburger.files.wordpress.com/2009/03/funny-pictures-your-cat-is-bursting-with-joy1.jpg', 'href': 'http://bit.ly/187gO1'}]
         },
         action_links: [
           { text: 'VOTE', href: 'http://github.com/facebook/connect-js' }
         ],
         user_prompt_message: 'Share your thoughts about Connect'
       },
       function(response) {
         if (response && response.post_id) {
           alert('Post was published.');
         } else {
           alert('Post was not published.');
         }
       }
     );
    }
    
    • minhee says:

      Hi, I’m really thank you and JK.
      This is what I want exactly.

      But I have one question.
      Can I use FB.api to publich like that?

      Becuase I need to publish to other page not Login ID’s default page.

      I can set page ID when I use FB.api. So I wonder I can set page ID when using FB.ui.

      Thanks!

  32. Chuck says:

    Thanks JK, thanks Mahmud

    I copy/pasted your code but it does not seem to work. I’m not even getting the alert so I think I’m not calling the javascript function properly. I’m calling the saySomething() function using something like Click here but nothing happens. Do you guys have any idea why ?

    Thanks !

  33. Jk says:

    Hi Chuck,

    In my case I called the saySomething(myMessage) function through a flash file. If you remove the parameter “mymessage”, the function saySomething() should work properly. Are you sure you request the needed permissions?

    Here is my demo page : http://www.thelbc.be/test/fb/index.html

    Here is my JS file : Here is my demo page : http://www.thelbc.be/test/fb/myfunction.js

    Hope it helps! Let me know.

    J.

  34. Chuck says:

    Sorry for the multiple posts.

    I found the problem : there’s a missing “}” character at the end of the function.

    Now what happens is that it prompts a window asking the user if this is what he wants to publish on his wall. But actually, I already got the permission to post on his stream on a previous page, so I would rather not prompt anything at all and get this posted on the user stream automatically. Do you know how I can do this ?

    Thanks

  35. mahmud ahsan says:

    @Chuck, yeah you can do that using graph api. Checkout in this post’s 2. How to use graph api part and graphStreamPublish() method. Modify the method, remove the alert part and call the method whenever you want to publish. If you want to do the task using php then check my other article http://thinkdiff.net/facebook/php-sdk-graph-api-base-facebook-connect-tutorial/

  36. Tom says:

    Thanks, Mahmud. The best API intro I have ever found for facebook. Quick question for you. I used your demo codes on secure site, however, when I tried “publish wall post”, the popup box is in dark color instead of white color. When I clicked the box, the whole page redirected to facebook and after I publish the message, the browser is blank with the page tile “XD Proxy”. Do you know why? and how to solve the problem?

  37. Lourdes says:

    Hi mahmud. First off great example! I loved every it! I did have a question though. I had a question about the friendsLocation() function you posted in the comment section. When I tried to implement it I would have occasions where I would get name => undefined, or the hometown will be completed missed (as in it’s listed on the person’s page but it’s not captured in the output). Would you happen to know why? Thanks!

  38. sookkien says:

    hi mahmud. Your example is so great to us. I have an question, how did the facebook connect using graph api work with the facebooktoolkit. I have face the problem to synchoronous the session.

  39. mwafi says:

    thanks Mahmud, very helpful post.

  40. sookkien says:

    @mahmud, facebook toolkit is available on this link http://facebooktoolkit.codeplex.com/ .

  41. mwafi says:

    @mahmud, you forget close tag “” in the first code sample for loading js sdk

  42. Sukura Hayuiw says:

    This doesn’t work. I copy and paste the code in a file “1.html” … I connect to facebook but the message to approve the aplication (“approve this permission”) doesn’t appear. Appears an error – http://s2.subirimagenes.com/imagen/previo/thump_4500453errorfacebook.png.

    I don’t know what happen, but your demo works … maybe I missed a file ?

  43. Chris says:

    Sukura – you probably just need to update the appId so that it’s using your own.

  44. Sukura Hayuiw says:

    Yes, you’re right. I changed the appId but now I’ve got another problem. This is the error:

    API Error Code: 100
    API Error Description: Invalid parameter
    Error Message: next is not owned by the application.

    http://s3.subirimagenes.com:81/otros/previo/thump_4503796errorfacebook2.jpg

    • mahmud ahsan says:

      @ Sukura Hayuiw, if you develop canvas base facebook application then you couldn’t provide the next parameter. I found this shows the error. Though in fbconnect project next parameter is allowed.

  45. Sukura Hayuiw says:

    hmmm well … but I went to settings, migrations and New Data Permissions was enabled … I put in disabled. After I went to Canvas and I put “http://www.google.com/” or anythin in Canvas Callback URL and Post-Authorize Redirect URL.

    At last, I put http://www.domainexample.co/files/ in Connect, Connect URL. Finally the app worked. Really I don’t understand what happened … could anyone explain me ?

  46. Ahmed Sabbour says:

    I don’t want to bug you, but I couldn’t find the answer to this anywhere.

    I followed your steps, but when I click on the Login button, nothing happens and I’m getting

    “FB.login() called before calling FB.init().”

    in the Firebug console.

    Do you have any idea??

  47. mahmud ahsan says:

    @Ahmed, did you check my full source code ?

  48. Ahmed Sabbour says:

    Yes I did :)
    I just found the problem, I was loading the AppId from the Web.config, but I was passing the wrong key to the AppSettings array.. (it was FBAppKey and I was looking for FBAppId)

    FB.init was failing silently

    more and more I love strongly typed stuff..no room for suck errors

    Thanks :)

    Do you happen to know how can I use and set a redirect url that facebook should redirect the user to after authentication?

    I’ve been doing it by linking to a url on my server that issues a server redirect to facebook’s servers using the following url format:
    https://graph.facebook.com/oauth/authorize?client_id={1}&redirect_uri={2}&scope={3}
    passing in my appid and a redirect url and a comma separated list of extended permissions

    Oh well..there are so many ways to do stuff using this API and so little documentation..

  49. Fran says:

    Hi Mahmud,
    using your code to login against FB, I have an issue using Firefox and Chrome in Windows, becuase in Linux is working properly.

    After click on the pop.up window to validate the user, the window is not closing properly and charge my web page double. In Safari work fine too. :(

    http://www.perceptica.com.mx

    Could you try to login in my page?

    Thanks,
    Fran

    • mahmud ahsan says:

      I’ve just tried your url in my windows 7 firefox 3.6. The fbconnect button working nicely and the popup hides after I approve it. I don’t see any problem of your link in my firefox in windows 7 and ubuntu 10.

  50. Jk says:

    @Fran

    On Firefox & Safari on OS X, it works fine!

    Jk.

  51. Fran says:

    Great!! I don’t have OS X. :-)

    Also my windows is XP

  52. ang says:

    Thanks for the post! Very very helpful

    I have a question, is your application counting the right number of user accesses? Are the total users and monthly active user number showing anything
    Thanks.

  53. Nick says:

    Great set of tutorials.

    It works great..Could you please help get the access token.

    Thanx,

    Nick

  54. buzzknow says:

    really great!

    this article better than official docs on Facebook, unbelieveable!

    thanks :)

  55. Gil says:

    Thank you for the tutorial
    I’m trying to retrieve comments
    I use your code and I run FQL query like you mentioned here.
    But the results I’m getting is only 1 comment
    how can I change it to view all the comments please?

    And here is the topic on the FB forums where you can see exactly what I want:
    http://forum.developers.facebook.com/viewtopic.php?pid=231957#p231957

  56. George Varghese says:

    Thank u for the tutorial.
    could u please tell me facebook log in window can be customized. if do it, how.

  57. HBR says:

    great tut. thanks.
    as buzzknow said, this is definetly better than the official docs.
    fb team has to seriously review their docs and the way they document their stuff.

  58. Sreekanth P says:

    really great

  59. Lance says:

    Thank goodness for this tutorial! I have searched far and wide for a simple tutorial that contains COMPLETE source code but minimal functionality (I prefer to start small and add features one at a time). No one (Facebook included) had (at least in obvious places) any full working basic Facebook Connect code. This code worked perfectly and was just what I was looking for. I was then able to expand your example to do exactly what I needed. Thank you so much!

  60. jon says:

    hello everyone.

    Frist of all thanks for this great tutorial. I found it very simple to use.
    I have a question that i haven’t been successful founding the right answer:

    How con i put in may application canvas a button that allows to add my application to an profile tab.

    i trying to run the fbxml on my body tag, but nothing is being rendered.

    Thanks for any help or guideline

  61. ccarrasco says:

    hi !
    sorry but, how to login user with a javascript function ? no with login button

  62. wallce says:

    hi all,

    Any idea how to use the PHP-SDK to bookmark an application?

  63. Yariv Habot says:

    Thanks for this tutorial, it’s much more readable than facebook’s docs.

    Could you please share your facebook app settings? What is your connect URL?

    I’m asking because I get the login button just fine, and the popup dialog does proper login and authorization, but then facebook redirects to my connect page, where that login button is, and shows it inside the popup window. Do I need to close that window myself and reload the parent window?

  64. vick says:
    —–I want to stream my information via input:

    input name=”input” type=”image” class=”float_rechts” onclick=”streamPublish(”,{‘name’:'NAME’,'href’:'http://stuttguide.de’,'description’:’ BESCHREIBUNG’,'media’:[{'type':'image','src':'','href':'LINK'}]},null);return false;” src=”../../../layout/fb/fb_small.png” width=”13px” height=”13px” alt”Pinnwand” title=”ab auf die Pinnwand” /

    ——and not through the script:

    function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
    FB.ui(
    {
    method: ‘stream.publish’,
    message: ”,
    ‘attachment’: {
    ‘name’: ‘name’,
    ‘caption’: ”,
    ‘description’: ‘(description)’,
    media: [{ 'type': 'image', 'src': 'http://icanhascheezburger.files.wordpress.com/2009/03/funny-pictures-your-cat-is-bursting-with-joy1.jpg', 'href': 'http://bit.ly/187gO1'}],
    ‘href’: ‘http://stuttguide.de’
    },
    action_links: [
    { 'text': 'hrefTitle', 'href': 'http://stuttguide.de' }
    ],
    user_prompt_message: userPrompt
    },
    function(response) {

    });

    }

    How can i do that?

    • mahmud ahsan says:

      please learn how to retrieve information from html code using javascript and to pass any javascript function.

      • Songbird says:

        Mahmud,

        This article is what I am looking for after a whole day looking in vain in Facebook forum.

        One question… How to get the user Facebook ID after the user logins in? I need to save this ID to the database.

        Any idea will be appeciated.

        Songbird

  65. jo says:

    @mahmud ahsan

    I have a question.

    How could I get an connected friends on facebook?

    I sucessed to call my friends list, but i’d like to know who is connecting on Facebook.

    Here is my code what call my friend list.

    ============ MY CODE ===========
    function callFriendList(){
    FB.api(‘/me’, function(response){
    var query = FB.Data.query(‘SELECT uid, name, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1={0})’, response.id);
    var html = ”;
    query.wait(function(rows){
    FB.Array.forEach(query.value, function(row){
    html += ”
    + row.name
    + ‘ ‘ + “”
    + ”;
    });
    document.getElementById(‘fqltest1′).innerHTML = html;
    });
    });
    }

  66. Carol X says:

    Is there any way to set the application cookie domain at FB.init, like you do with the PHP SDK?

  67. RasByZ says:

    nice article
    thx a lot

  68. Kellie says:

    Thanks for the tutorial! I was able to get most things working, but unfortunately am still unable to post an attachment via the following method: FB.api(‘/me/feed’, ‘post’ …);

    I tried the following code provided in a comment above but it doesn’t work. The message body gets posted, but not the attachment

    var attachment = { ‘name’: ‘i\’m bursting with joy’, ‘href’: ‘ http://bit.ly/187gO1‘, ‘caption’: ‘{*actor*} rated the lolcat 5 stars’, ‘description’: ‘a funny looking cat’, ‘properties’: { ‘category’: { ‘text’: ‘humor’, ‘href’: ‘http://bit.ly/KYbaN’}, ‘ratings’: ’5 stars’ }, ‘media’: [{ 'type': 'image', 'src': 'http://icanhascheezburger.files.wordpress.com/2009/03/funny-pictures-your-cat-is-bursting-with-joy1.jpg', 'href': 'http://bit.ly/187gO1'}] };

    FB.api(‘/me/feed’, ‘post’, { message: body, attachment: attachment}, function(response) …

    Can someone please let me know if they were able to get it working?

  69. Colin Wren says:

    Thanks for the excellent tutorial. After following another tutorial in a published magazine which didn’t work your tutorial helped me make my app.

  70. Ed says:

    Would love to figure out how to implement into wordpress? Any suggestions…I really need the login/logout to work…thanks

  71. eli says:

    thanks for the post

    I am working with some templates so when user logs in redirects to other .php file and to other page.

    although I have :

    It only give me the basic user’s details .

    I need user to approve for my application to get his email .
    It completely ignores the “perms” ,how can I get a users email address .

    please help

    • mahmud ahsan says:

      If your user approves email permission when approving the app, you can easily retrieve his uid vai FQL query or calling api.

      • eli says:

        that’s the thing that ,is not requiring the extended permissions (email) , but only allows the basics .

        the “perms” parameter is completely ignored.

        I looked around and I see that face book now changed their policy and now they using some kind of URL to get a token …
        I don’t know how this could be implemented , and their documentation sucks .

        thanks for your help

  72. ccarrasco says:

    Hi Mahmud
    why in my stream Publish Box show me a “red line”, check this plis : http://grab.by/5hgQ

    thanks for your help

  73. Jeff says:

    Do you have an example of how to get the e-mail if a user allows the site to have the e-mail address? I can’t seem to get anything to work.

  74. Songbird says:

    Mahmud,

    Follow up with choosing either Javascript SDK or server side implementation of OAuth 2.0… My site is a asp.Net MVC web application. The requirement is to port facebook user identity to my site. That’s why I need to save the facebook User ID to the database and link it with site user identity.

    I am thinking the server side may be suitable for the authentication. Do you have sample for server side implementation?

    Also when a user logs out, how to verify that a user is indeed logs out of facebook?

    Thanks much,
    Songbird

  75. oNNo says:

    Cool. Thanks for the solution.
    Is the new graph API backward compatible with the old FB javascript API?

  76. Neetu says:

    Hi,

    using js-sdk how we get friend list ?

  77. Khalid says:

    Hi Mahmud,

    Thanks a lot for this great tutorial. i just have a question, how is it possible to post an image in user’s photo album? I am trying to allow users to make an image as their profile image. Your help is appreciated.

    Thanks

  78. Khalid says:

    Thanks Mahmud, I managed to do this and it is brilliant :)

    Regards

  79. david says:

    fb app can invite friends to join our app ,
    but in fb connect , can it invite friends to join our app ?
    thx!!!

  80. Arvi says:

    Thanks for the tutorial! I have some questions though…

    In the PHP SDK, there is the next and cancel parameter for login, how do I this Javascript SDK? I want to redirect the user to account creation instead of the same page, I know how to do this in PHP SDK but I’m trying to use the Javascript SDK…uh-oh I’m stucked. Thanks.

  81. Jeff says:

    I have my application doing the user authentication and permission logic. All of that works great (thanks to this example). But I want the application to post messages to a fan page that I’m creating. I keep on hearing that a fan page is available through the application but I can not find where to access it. Is there a fan page for the application? If not how can I write to the wall of the fan page from the application?

  82. venkat says:

    Hello Mohmud,

    I am able to exicute app. But very first time after logging in to the facebook it is hanging at a popup page “http://static.ak.fbcdn.net/connect/xd_proxy.php”.

    How can I get rid of this window and it should diappear.

    Please help me.

    Thanks,
    Venkat.

  83. @Mahmud vai, Really awesome post. Very helpful and make my life much easier :)

  84. Jashwant says:

    I want to display all friends of a user by javascript graph api .

    I am using following code.

    function fqlQuery(){

    FB.api(‘/me’, function(response) {
    var query = FB.Data.query(‘SELECT uid,name,pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=’+ response.id);
    query.wait(function(rows) {

    document.getElementById(‘name’).innerHTML =
    ‘Your name: ‘ + rows[0].name + “” +
    ” + “”;
    });
    });
    }

    Is it because my query will result multiple results ??? Please provide me a way to accomplish this

  85. Jeff says:

    I want to find out if the logged in user has liked a fan page…

    How do I do this using the FB.api?

    FB.api(‘/me/fanpageid’)
    response.???

  86. ven says:

    Hello Mahmud,

    Thank you for the post, It is really helpfull for me.

    I am able to exicute app. But very first time after logging in to the facebook it is hanging at a popup page “http://static.ak.fbcdn.net/connect/xd_proxy.php”.

    How can I prevent this window.

    Please help me.

    Thanks,
    Venkat.

  87. Venu says:

    Hi Mahmud,

    Thanks for the article! I’m building an iphone app which uses FBConnect. However I have a more basic protocol question. I’m able to post stories to the wall/news feed. But I don’t know how to get the id of the post I just publish so that I can retrieve comments from it later on. I’m sure I’m missing some basic information of the protocol, can you please let me know how to solve my problem.

    Thanks in advance,
    Venu

    • mahmud ahsan says:

      Are you using Objective C library by facebook? In php using api when you publish something on user’s wall the api method returns the post id.

      • Venu says:

        Hi Mahmud,
        Thank you for the quick reply. I am using Objective C and kind of new to it. I’ll sure explore it a little more if I’m getting any response back from the server.

        Thanks again!
        Venu

        • Venu says:

          Hi,
          I was able to finally get the id of the post back from the call itself! Thanks for letting me know initially!

          Venu

  88. Sandi says:

    Hi mahmud ahsan,

    Thanks a lot. u know before i found your tutorial, i wasted three days to research for this.

    Thanks again.
    sandi

  89. Sandi says:

    hi,
    can u pls help me? how to upload video by using method: ‘video.upload’ in FB.api ?

    Thanks and Regards,
    sandi

  90. Tayo says:

    Hi,
    Am a a college student working on a project. my idea of the experiment is to use my friends information on facebook as a means of authentication. when my frinds visit my website, to log into my site i ask them a few questions from thier facebook information like 1.how many friends did u add last week 2. how many friends request did u recieve 3. how many pictures did u add etc. if the answer from my frineds is correct, then they can fully log into my site to play a game and do a survey.
    Its just an academic experiment. But i need the api to collect the data for my database so that i can confirm the answer is correct each week for example.
    I have read about graph api but your tutorial is very good though am not a developer.
    would i be able to use this api for the purpose above. could you give me a guide on how to implement it?

  91. RJ says:

    Hi guys. I’m getting this error.

    API Error Code: 100
    API Error Description: Invalid parameter
    Error Message: next is not owned by the application.

    What exactly should I put on the Canvas URL, Post Authorize, Base Domain etc.?

  92. Venu says:

    Hi Mahmud,

    Can you please let me know if we can make an AJAX call using the action link feature present in the stream post?

    Thanks,
    Venu

  93. Adnan says:

    nice stuff very help full ………. thanx :)

  94. AlexB says:

    Firstly can I say what a great tutorial this is. I got to about half way in 2 days but your tutorial saved me a heap of time.
    I am developing an app in grails, alas, and not php, so I have a client server requirment. Once a user is logged in, I then need to somehow inform the server side that this is the case. Is the best way to achieve this, by looking for the cookie and pulling the info from that or would you simply post the facebook UID in a form to the server… Once again, many thanks.

  95. jsherk says:

    Thanks so much… I was able to figure out how to get an access token with the Graph API, but I could not figure out how to get my application Authorized so it actually access information!!

  96. waris says:

    HI fb gurus.
    i want to get user’s friend then using their uid, have to get selected friend albums and then i want to get photos of selected album. see example here http://apps.facebook.com/casio_exilim/
    what i want. i have to use facebook with graph api like
    FB.Api(‘/uid/albums’, response () {
    //here have to parse returned data.
    })
    Any help and reference is appreciated.
    Thanks

    • waris says:

      @addition on my above question. My app will be standalone version on website using facebook connect and same will be as canvas iframe app

  97. JT says:

    Thank you for this tutorial!

  98. Bill says:

    This was really helpful. Thanks.

  99. orientsilver says:

    very very good tutorial, unlike other crap on google that contais old & unuseful ones. thank you!

  100. Joe says:

    Hello Mahmud,

    very good article Appriciate. it lot useful for me.

    I have implemented few functions.

    I am stuck at stream publish. I am able to publish posts with lot of key/value’s (ex: message, properties, category, description etc). My problem is I would like to retrive the entire post information. I am able to get only message. but I need to retrieve all key/vaule’s. can you please help me here in which table those values store and help me with fql example.

    Thank you.
    joe

  101. Adrian says:

    Thankyou so much for this post, i wish you did it years ago ;)
    the facebook examples are not very good but yours works straight away!

  102. amit says:

    hi there mahmud :)

    Your blog is a hit! thanks for this post as well, it is very very helpful.
    I am having a small problem and will be glad to get your advice.
    I am trying to make an auto post and attached it an image. Means, posting a message without getting the editor pop up message…
    In other words, can I use for example the setStatus() method and attached an image aside of a text? or should I use other way to do an auto update?

    Thanks in advanced!!
    amit

    • mahmud ahsan says:

      amit, when you want to auto publish, you have to seek offline_access and publish_stream extended permissions from user. Get idea from here http://thinkdiff.net/facebook/update-facebook-page-status-automatically/ but you have to use facebook latest library because at the time i wrote that tutorial I used facebook old library.

      • amit says:

        thanks mahmud.

        I am actually having these permissions embedded and the ‘publish.stream’ goes well but I would like to cancel the ability to give a user to edit the message box and do it behind the stage.

        when I am using the status update method it works well but I would like to attach an image to it.

        do you know how to attach an image when updating my status? I am using the ‘status.set’ method:
        FB.api({method: ‘status.set’, status: status1})

        thanks again :)

  103. jitendra says:

    thanks sir very nice code can u give some information how to access user information such as email, name, address etc to another page like registration.aspx and save it my application .please reply soon ………thanks again n again …..

  104. Jeff says:

    Thank you!!! I am doing this for a few days and finally find your tutorial!! You are so great to make this!!

  105. Kumar says:

    Is it possible to use the javascript sdk in a local HTML file (not served through a web server) ? If yes, in this case, what would be the application settings wrt the the callback and canvas URLs?

    Also, how are facebook desktop clients implemented ? They too are not tied up to a URL.

    I’m a newbie to web development, please excuse if these are trivial questions.

  106. Rupak says:

    You rock man….It takes 5 minute to setup facebook application….thanks for the document….

    grate work!!!!!!!!!!!!!!!

Leave a Reply