Graph api & javascript base Facebook Connect tutorial

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

UPDATE: Checkout Updated Post From Here

Below is the old post, so leave it.

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 web host. 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>

:)

About mahmud ahsan

Programming is my passion from high school. I always looking for innovating new ideas and making them real application. I love mobile application and game development as well as web development. Having 4+ years web development experience and 6+ years mobile application development experience on different platform and business on it. My Mobile Apps Portfolio: iThinkdiff.net Mobile Apps

, , , , , , ,

222 Responses to Graph api & javascript base Facebook Connect tutorial

  1. maSnun May 1, 2010 at 11:34 am #

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

  2. mahmud ahsan May 1, 2010 at 11:47 am #

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

  3. sertac May 1, 2010 at 4:51 pm #

    very successful code thanks for sharing with us

  4. Ghido May 1, 2010 at 5:06 pm #

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

  5. mahmud ahsan May 1, 2010 at 10:11 pm #

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

  6. ccarrasco May 2, 2010 at 4:37 am #

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

  7. Ghido May 2, 2010 at 4:33 pm #

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

  8. James May 3, 2010 at 4:07 am #

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

  9. Donavan May 3, 2010 at 11:46 pm #

    This is a great intro to facebook api

  10. Chuck May 4, 2010 at 1:07 am #

    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 May 4, 2010 at 2:25 am #

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

    • Daniele December 2, 2010 at 6:46 pm #

      I just tried your suggestion but the attachment is not published.
      how can I fix this?

  12. Mike May 4, 2010 at 2:32 pm #

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

  13. mixnovich May 5, 2010 at 11:02 pm #

    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 May 6, 2010 at 12:21 am #

    @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 May 6, 2010 at 2:34 am #

    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 May 6, 2010 at 3:10 am #

    @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 May 6, 2010 at 11:47 pm #

    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_ May 7, 2010 at 12:28 pm #

    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_ May 7, 2010 at 12:29 pm #

    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 May 7, 2010 at 2:33 pm #

    @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 May 7, 2010 at 11:33 pm #

    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 May 7, 2010 at 11:53 pm #

    @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 May 8, 2010 at 12:13 am #

    Thanks mahmud .

  24. mixnovich May 8, 2010 at 12:13 am #

    Thanks mahmud .
    i am making the correction right away

  25. sarfraz ahmed May 8, 2010 at 3:05 pm #

    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 May 8, 2010 at 5:00 pm #

    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 May 9, 2010 at 12:08 am #

    @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 May 9, 2010 at 1:54 am #

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

  29. Chuck May 11, 2010 at 4:36 am #

    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 May 11, 2010 at 5:01 am #

    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 May 11, 2010 at 1:07 pm #

    @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 June 12, 2010 at 4:00 pm #

      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 May 11, 2010 at 10:12 pm #

    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 May 11, 2010 at 10:40 pm #

    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 May 11, 2010 at 11:38 pm #

    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 May 12, 2010 at 12:50 am #

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

    • Mattias November 2, 2010 at 10:05 pm #

      First of all! Thank you. This tutoriual is great.

      I have a question and I can’t find the answer in the comments.

      I want to use the graphStreamPublish function to without a prompt post a feed with an attachment. I can’t get that to work. I can get that to work with your function showStream but than the user get the prompt. Any solutions?

    • Rudy November 3, 2010 at 4:54 pm #

      Hi,

      I tried to follow every step of this great tutorial and I still could not figure out how to publish the users’ wall automatically with pop up. Is is possible to work that out ?

      Thanks!

  36. Tom May 12, 2010 at 11:03 am #

    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?

    • mahmud ahsan May 12, 2010 at 1:14 pm #

      @Tom, I never worked this code for secure site. Would you correctly set the FBConnect url setting to your secure site ?

  37. Lourdes May 12, 2010 at 1:09 pm #

    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 May 13, 2010 at 9:21 am #

    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.

    • mahmud ahsan May 13, 2010 at 10:58 am #

      @sookkien, what is facebook toolkit?

  39. mwafi May 13, 2010 at 2:53 pm #

    thanks Mahmud, very helpful post.

  40. sookkien May 13, 2010 at 3:50 pm #

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

  41. mwafi May 13, 2010 at 4:41 pm #

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

  42. Sukura Hayuiw May 14, 2010 at 3:05 am #

    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 May 14, 2010 at 5:13 pm #

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

  44. Sukura Hayuiw May 14, 2010 at 10:18 pm #

    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 May 14, 2010 at 10:33 pm #

      @ 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 May 14, 2010 at 10:44 pm #

    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 May 18, 2010 at 3:55 pm #

    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 May 18, 2010 at 4:08 pm #

    @Ahmed, did you check my full source code ?

  48. Ahmed Sabbour May 18, 2010 at 4:36 pm #

    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 May 18, 2010 at 10:48 pm #

    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 May 18, 2010 at 11:24 pm #

      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 May 18, 2010 at 10:51 pm #

    @Fran

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

    Jk.

  51. Fran May 18, 2010 at 10:54 pm #

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

    Also my windows is XP

  52. ang May 18, 2010 at 11:49 pm #

    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 May 19, 2010 at 4:14 am #

    Great set of tutorials.

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

    Thanx,

    Nick

  54. buzzknow May 22, 2010 at 9:08 pm #

    really great!

    this article better than official docs on Facebook, unbelieveable!

    thanks :)

  55. Gil June 1, 2010 at 7:42 pm #

    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 June 3, 2010 at 5:18 pm #

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

  57. HBR June 4, 2010 at 4:48 pm #

    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 June 10, 2010 at 1:26 pm #

    really great

  59. Lance June 11, 2010 at 9:23 am #

    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!

    • mahmud ahsan June 11, 2010 at 4:19 pm #

      Its my pleasure to know that it helps you.

  60. jon June 14, 2010 at 4:49 pm #

    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 June 15, 2010 at 2:26 am #

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

  62. wallce June 15, 2010 at 5:33 pm #

    hi all,

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

    • mahmud ahsan June 16, 2010 at 12:30 am #

      Please check this link http://wiki.developers.facebook.com/index.php/Fb:bookmark there is no php api for bookmarking.

      • Pandu July 9, 2010 at 12:27 am #

        Hi Mahmud…so there are no way to get fb bookmark button in iframe application?

        I’ve try this method on my iframe app
        Tes

        It’s only show the “Loading” box for a second then it dissapeared…what possibly wrong with this code?
        Thx in advanced for you help.

        • Pandu July 9, 2010 at 12:30 am #

          Sorry…i mean this code :

          < a href="javascript:void(0);" onclick="FB.Connect.showBookmarkDialog();" requirelogin="1">Tes< / a >
  63. Yariv Habot June 15, 2010 at 11:41 pm #

    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 June 16, 2010 at 11:19 pm #
    —–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 June 17, 2010 at 1:05 am #

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

      • Songbird June 23, 2010 at 3:55 pm #

        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

        • mahmud ahsan June 23, 2010 at 6:05 pm #
          FB.api('/me', function(response) {
             var uid = response.id;
          });
          
          • Songbird June 26, 2010 at 2:16 am #

            Thank you so much. This is a great example of log-in on client side. What’s your opinion doing this on server side using the Graph API provided by Facebook. Pros and Cons?

            thank you again,
            Songbird

          • mahmud ahsan June 26, 2010 at 2:52 am #

            I use both when i need both :) It depends on the application interface and requirements.

  65. jo June 17, 2010 at 2:57 pm #

    @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 June 20, 2010 at 4:33 am #

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

  67. RasByZ June 24, 2010 at 1:19 am #

    nice article
    thx a lot

  68. Kellie June 24, 2010 at 3:24 am #

    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 June 25, 2010 at 5:03 am #

    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 June 28, 2010 at 10:27 am #

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

  71. eli June 30, 2010 at 9:04 pm #

    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 July 1, 2010 at 12:04 am #

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

      • eli July 1, 2010 at 3:58 pm #

        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

        • eli July 1, 2010 at 4:00 pm #

          I use fb:login-button v=”2″ size= “small” perms=”email”

  72. ccarrasco July 6, 2010 at 3:10 am #

    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 July 6, 2010 at 11:26 am #

    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.

    • mahmud ahsan July 6, 2010 at 3:08 pm #

      If user approves your site, and if you set email permission during authentication only then you could retrieve user’s email.

      FB.api('/me', function(response) {
      	  alert(response.email);
      });
      
      • Jeff July 6, 2010 at 7:39 pm #

        @mahmud that worked perfectly. Thank You!

  74. Songbird July 6, 2010 at 3:04 pm #

    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 July 7, 2010 at 3:57 am #

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

    • mahmud ahsan July 7, 2010 at 10:08 am #

      Old javascript api library still works, but facebook recommends to use the new javascript api.

  76. Neetu July 7, 2010 at 1:53 pm #

    Hi,

    using js-sdk how we get friend list ?

    • mahmud ahsan July 7, 2010 at 3:44 pm #
      FB.api('/me/friends', function(response) {
      	//here response will be json array object that will contains loggedin users friends ids and names
      });
      
  77. Khalid July 7, 2010 at 5:15 pm #

    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 July 8, 2010 at 3:57 pm #

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

    Regards

  79. david July 8, 2010 at 11:33 pm #

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

    • mahmud ahsan July 10, 2010 at 1:48 pm #

      Yeah you can use the same xfbml code to make invite box and the invite functionality.

  80. Arvi July 13, 2010 at 10:37 am #

    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 July 16, 2010 at 1:09 am #

    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 July 17, 2010 at 2:10 am #

    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. Kazi Abdullah Al Mamun July 19, 2010 at 5:16 pm #

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

  84. Jashwant July 20, 2010 at 8:55 pm #

    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 July 24, 2010 at 11:52 pm #

    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 July 25, 2010 at 12:00 am #

    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 July 25, 2010 at 4:38 am #

    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 July 25, 2010 at 4:14 pm #

      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 July 26, 2010 at 2:14 pm #

        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 August 3, 2010 at 4:19 pm #

          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 July 26, 2010 at 4:31 pm #

    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 July 27, 2010 at 6:11 pm #

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

    Thanks and Regards,
    sandi

  90. Tayo August 1, 2010 at 10:56 pm #

    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 August 2, 2010 at 3:41 pm #

    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 August 3, 2010 at 4:18 pm #

    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 August 4, 2010 at 7:20 pm #

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

  94. AlexB August 5, 2010 at 6:09 pm #

    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 August 7, 2010 at 8:35 am #

    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 August 7, 2010 at 1:21 pm #

    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 August 7, 2010 at 1:24 pm #

      @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 August 10, 2010 at 4:08 pm #

    Thank you for this tutorial!

  98. Bill August 10, 2010 at 5:56 pm #

    This was really helpful. Thanks.

  99. orientsilver August 14, 2010 at 2:40 am #

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

  100. Joe August 17, 2010 at 8:18 pm #

    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 August 20, 2010 at 7:06 am #

    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 August 24, 2010 at 7:26 pm #

    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 August 24, 2010 at 9:09 pm #

      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 August 25, 2010 at 1:48 am #

        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 August 27, 2010 at 7:59 pm #

    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 August 30, 2010 at 2:46 pm #

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

  105. Kumar August 30, 2010 at 9:48 pm #

    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 August 31, 2010 at 1:24 am #

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

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

    • Rob September 13, 2010 at 10:17 am #

      Rupak,

      How did you get yours up and running? Did you just change your appID? If so, how did you get past this error:

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

      Cheers,
      Rob

  107. ali September 6, 2010 at 11:33 pm #

    thanks a lot man – your rock!

    I am the developer of profile song application on facebook, the application is written in FBML and java background but since facebook has announced that they are going to stop supporting the FBML soon I’m trying to change it to IFRAME.

    I am trying to follow your blog to change the application to IFRAME but i have some difficulties – I can’t exactly copy/paste your code since my code is in java, so I really appreciate if you can help me with some questions!

    – when i try to submit a form from the iframe, the request does not contain the session key! but I need to find the logged-in user so I can access his data, what do you suggest? are you keeping those information in the backend or front (in the session or cookie for example) or passing them around once you have it?

    – if that is the case, what is the solution to the expired sessions? let’s say, i receive a form submission, i get the fb_session id from the form or from the internal session and let’s say that session is expired, then i probably have to redirect to the login page to the get a new session – how can i access the form data again? are they lost? or can i pass them to the login url and get them back again?

    I really appreciate your help
    if you have a overal how to (doesn’t have to be cod) steps and send it to me i really really appreciate it

  108. kanedogg September 8, 2010 at 7:09 am #

    Dude nice example, tutorial the work is pretty good stuff. Although if you take notice 80% of your code functions are straight from the facebook jsSDK website. streampublish and share are exactly what FB shows, but otherwise it is a good example, cheers.

  109. Irina September 8, 2010 at 7:10 pm #

    Great tutorial, thanks for sharing!

  110. photoCoup September 12, 2010 at 11:40 am #

    Can’t thank you enough for this incredibly helpful tutorial and demo. This was a million times easier to work with than the Facebook documentation!!

  111. Tony September 13, 2010 at 12:14 am #

    Great Tutorial.
    When I try to post, it posts to my personal profile.
    How can I direct the post to my fan page?

    Thanks

  112. Rob September 13, 2010 at 10:02 am #

    Thank you so much for this! FB documentation is absolutely unruly. Like everyone else, I need some help. I’m just trying to understand how to replicate exactly what you have with my own ID. But, when I put my FB appID in there the login no longer works and I get a: “API Error Code: 100″. I read others had this (above), but there was no resolution to their request.

    Also, in your tutorial, only the “login, “publish to wall” and “share with friends” are working.

    Any idea how to fix this?

    • Rob September 13, 2010 at 12:26 pm #

      I figured it out (for those of you with the same problem). Because of the new “Site Domain” setting in “Website Settings” of your application, you have to “test” the code on your actual domain (or whatever domain you put in your settings).

      Good luck!

  113. Rob September 13, 2010 at 12:27 pm #

    And by test it, I mean:

    If your settings are: mydomain.com

    Then you need to upload your code to your domain (mydomain.com) and test it from there.

    Alternatively, you can change your settings to localhost (I didn’t try this, but I read about it).

    Good luck!

  114. Krupa September 16, 2010 at 1:38 pm #

    Awesome post. It helps a lot for basic facebook connect.

    Hope you will post on some new interesting points,

    Happy Posting, :)

  115. Khawar Abbasi September 17, 2010 at 12:12 pm #

    How can I get user picture

  116. laxmikant September 17, 2010 at 4:45 pm #

    When i used this new fb api,

    i am not logined with Facebook, after enter username and password in fb login window its get stuck at xd_proxy in IE 8. in same popupup.

    can u help me

    where is issue?

    • Rajesh September 18, 2010 at 8:35 pm #

      @Laxmikant – i am facing the same problem ,

      @mahmud ahsan – Can you please help us – i am facing the same problem also i post this on the facebook forum but i think FB Developer sleeping.. very bad things.

  117. Khawar Abbasi September 20, 2010 at 12:23 pm #

    @Mahmud ahsan –
    Realy great post. Once facebook connect made frustrated from development as I was trying to integrate using codigniter. U made it possible for me. Thanx again. Just help in last issue that is can I use custom login / logout button. I’ve very close deadline, so plz help me as soon as possible.

    • mahmud ahsan September 21, 2010 at 3:04 am #

      Definitely you can use custom login/logout button.

  118. Jayesh September 22, 2010 at 4:29 pm #

    HI Mahmud,
    I went through your site and I found it most valuable because what u told is working :).. I had 1 question to ask. Can we open fb:dialog in an IFRAME Canvas App in Facebook??? Your reply will be appriciated..

  119. Glass September 22, 2010 at 8:23 pm #

    Good material, I found this via StumbleUpon and I must tell about it to others myself also. Thanks a lot mate!

  120. Jayesh September 23, 2010 at 11:39 am #

    Thanks Mahmud for your quick response.. Will try in my app and let you know…..

  121. Jayesh September 23, 2010 at 5:58 pm #

    Mahmud, can you give some sample code using jquery dialog box like facebook. I am struggling hard as I am not new to jquery…

  122. Mike Dennison September 24, 2010 at 4:03 am #

    Thanks very much for this tutorial – it has been a great resource. I’m hoping you can help me with one small issue. I am building a mobile site that uses Facebook connect and I need my permission/login pages to use m.facebook.com instead of http://www.facebook.com. I can’t seem to figure out how to get this to happen. Any help would be much appreciated!

    Cheers,

    Mike

  123. George Alexander September 27, 2010 at 6:18 pm #

    I’ve been banging my head at the lack of proper documentation for facebook APIs until I hit upon your website. You’ve written some awesome tutorials. Great job! Will be a regular visitor on your site.

  124. Akhil Mordia October 2, 2010 at 3:45 pm #

    yaar thanks a lot… the world needs teachers like u… thanks a lot again.. i will mail facebook to include this tutorial in their API… facebook API sucks…
    only this tutorial makes it work properly… keep it up bhai…

  125. Ali October 3, 2010 at 2:28 pm #

    Thanks very much for this tutorial it helped me to developed my first Applcation. Actualy I’m in middle of that.
    I have a question about using facebook API:

    In registeration process I want to use user’s email and I I want to know that is user confirmed this Email on Facebook or not.

    I mean if user confirmed his/her email before on facebook, I don’t need to send confirmation Email to user because this request will be not welcome by users on my website/Application.

    I would be very thankful for your help

  126. Camilo Delvasto October 9, 2010 at 8:15 am #

    This tutorial simply made my day! I setup a subscribe page to phpList using Facebook Connect in a couple of hours thanks to you!
    All the best!
    Camilo

  127. md Aijaz October 15, 2010 at 6:44 pm #

    Thanks A TONNNNNNNNNNNNNNNNN!!!!!!!!

  128. Tim Nicholson October 15, 2010 at 9:28 pm #

    I have several FB apps, some with the old PHP API’s and some with the new Open Graph API’s and FB will be forcing iframe apps by the end of the year. Does anyone have any tips for minimizing javascript use in an iframe app and dealing with resizing the iframe and reloading different page URL’s instead of just updating all the content with javascript in the same window?

  129. Zack Esgar October 20, 2010 at 10:29 pm #

    you are a lifesaver

  130. Scott Leonard October 21, 2010 at 2:44 am #

    I’m looking for a way to programmatically send a ‘like’ request just as though the user clicked on the facebook ‘like’ button.

    Is there something like a ‘stream.like’ javascript API command that can be used to send this?

  131. alishakool October 24, 2010 at 11:42 pm #

    Without using appkey is it possible that from c# web application user can login to their facebook account using their email and password and gets their friendlist

    Please help me is there any solution
    Thanks

  132. Yoav October 26, 2010 at 3:36 am #

    Hi,
    thanks a lot for the great code and explanations. I have a question. Whats the meaning of this line: ” window.fbAsyncInit = function()” ?

    thx

    yoav

  133. Marcello October 29, 2010 at 6:55 am #

    Thank you so much!
    I have a question about this code

    (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);
    }());

    is there any reason why it is wrapped in () ? (I know the () after the } triggers the function but why the extra wrapping?

    • mahmud ahsan October 29, 2010 at 6:44 pm #

      function(){} is a function defination (function(){}); triggers the function.

  134. mauricio October 30, 2010 at 2:19 am #

    thank you very much!!! this give me a light hahaha
    all the other “tutorials” and “documentation” only gives me doubts! thank you!

  135. chris November 5, 2010 at 3:28 pm #

    hello,
    how can i use an array to display multiple links inside the “stuff” parameter

    function showStream(){
    FB.api(‘/me’, function(response) {
    //console.log(response.id);
    streamPublish(response.name, ‘stuff’, ‘hrefTitle’, ‘array’, “thinkdiff.net”);

    i was thinking to use:

    function publishStream(){

    streamPublish(“Vote for me here”, ‘Visit Explore Talent’, ‘Checkout’, ‘\n’, “Facebook Application”);

    }

    but it will not work

    thanks,

  136. Josub November 10, 2010 at 5:16 am #

    Hi, very nice tutorial, got me up and running. I used php sdk before but this suite me a lot better. One question though: How do you easily get and store a logged in users uid in order to fetch and display their name later for other users.

  137. dilsayar November 14, 2010 at 8:02 pm #

    Your tutorials are great and very detailed, good for beginners and advanced learners, thanks for taking your time for preparing and sharing them

  138. Matthew November 16, 2010 at 5:30 pm #

    Hi this is an excellent tutorial. I am trying to attempt to set a global var, i.e

    var firstname = “”;

    and then using …

    function login(){
    FB.api(‘/me’, function(response) {
    firstname = response.first_name;
    });
    }

    .. change/update the global variable with the response data. But it doesnt update. Can anyone help explain as to why this is?

    Thanks.

  139. Stefan November 18, 2010 at 3:24 pm #

    Great tutorial, thank you very much !!!!

    Stefan

  140. numan November 19, 2010 at 12:27 pm #

    I used some of the sample code, but I can’t see the fb login button rendered. Not sure what I’m doing wrong…

    Could it have anything to do with the app id domain name? I am running the code from localhost.

  141. rickdnomad November 22, 2010 at 10:29 am #

    Thanks very much. I should get you a dinner. I spent hours to get API working, and just could not figure out how to implement it until I see your website.

    So far this is the best tutorial for API implementation. Better than facebook itself.

  142. kali November 24, 2010 at 4:57 pm #

    Thanks for such a post but I am in need of a solution for posting into feed. Actually I want to include a link in description of post and I am using New Graph API and action script. So, in action script we are using api call like this:
    var params:Object = {
    message:”display message”,
    name:”name to be displayed”,
    link:”http://localhost/…”,
    caption:”caption to be displayed”,
    description:”Want to publish or delete?”,
    };
    Facebook.api(“/me/feed”,handlePostComplete,params,”POST”);

    What If I want to include a link in description.I tried entering Google BUT description doens’t show up Google in feeds on posting.

  143. Tony November 25, 2010 at 8:29 pm #

    I can get perm by using :

    function fblogin() {
    FB.login(function(response) {
    //…
    }, { perms: ‘email,user_birthday’ });
    }

    How do I REMOVE perms that I previously allowed.

    How do I know what perms I have given and to whom?

  144. Akangdesain November 27, 2010 at 6:09 am #

    thx … great tutorial ….
    how to update status page ?

  145. Yusuf November 30, 2010 at 5:43 am #

    Sir,
    i have used your javascript example it is working fine in website and in apps.facebook.com but when I added this in tab as iframe application, I am getting error external javascript call and I am not using any other javascript except which you have in your example

    do you know how can I implement this in tab as iframe application and do you have any example in c#
    Thank you

    • mahmud ahsan November 30, 2010 at 11:52 am #

      Facebook yet not support iframe in tab application but they will soon. So please wait until then or developed tab application according to their rules.

      • Yusuf November 30, 2010 at 9:20 pm #

        Thank you.

  146. Swathi December 3, 2010 at 12:23 pm #

    Hi
    How can I post messages to my friends?

  147. Swathi December 3, 2010 at 12:40 pm #

    When am clicking the link “Publish Stream Using Graph API” , am getting “an error occured”.
    Can u please help me

  148. mauricio December 7, 2010 at 5:10 am #

    hey man! what about ie 7 :( i´m having some troubles with this javascript sdk in ie7 ( i can´t just ignore it)
    and i tried this tuttorial but still having some troubles…can you give me some ligth maaan thanks a lot!

    • mahmud ahsan December 7, 2010 at 4:03 pm #

      I’m sorry to say that I use mac and don’t use iE.

      • mauricio December 8, 2010 at 3:40 am #

        same here! but i have to get it working on IE :C too bad! all the other browsers works perfeclty :/ thanks anyway! you’ve been very useful !

  149. surbhi December 9, 2010 at 10:46 am #

    one time successful code………………….

  150. Chris December 9, 2010 at 12:48 pm #

    This entire write up was incredibly helpful to me. Thank you so much, your examples were PERFECT.

  151. Riaz Ali December 9, 2010 at 2:50 pm #

    Hi, I have a game on my website and I want to share the score on wall facebook account wall. I have searched and found that it can be done with facebook connect, but through facebook connect I am able to share only URL of any page. So can kindly help me and tell how share “score and my custom message” through facebook connect. Thanks

  152. Swengr December 9, 2010 at 3:30 pm #

    Hi, Mahmud, you example tutorial is nice, but when I click the “Publish Wall Post” link then a pop-up window appears, but following error message is returned

    “An error occurred with Demo Application | Thinkdiff.net. Please try again later.”

    Also when I click “Publish Stream Using Graph API” button then a javascript alert is appears, that says “Error occured”. So please kindly tell the reason behind these errors and their solution. Thanks.

  153. Roderick December 12, 2010 at 5:59 pm #

    hi Mahmud,

    thank you a lot for the tutorial ,it is great!
    One question: i included the news feed from facebook (the first page you see when you login ) but that doesn’t show for example that USer B is now friends with User C. do you know how to show that?

    I did this to show the news feed:

    try {
    $newsfeed = $facebook->api(‘/me/home’);
    }
    catch(Exception $o){
    d($o);
    }

    I do get the rest! tHank you very much!

  154. Roderick December 12, 2010 at 6:01 pm #

    oh sorry i put it on the wrong page, i use the php one!
    sorry!

  155. Mike Haydon December 21, 2010 at 9:08 am #

    Thanks so much for this tutorial Mahmud! I’ve been tearing my hair out (metaphorically lol) over why my fb connect code wasn’t working. Now it all makes sense. Cheers.

    • mahmud ahsan December 22, 2010 at 12:33 pm #

      You’re welcome Mike.

  156. Kumar December 24, 2010 at 12:53 pm #

    Can you please tell me, how can we logout manually by placing one button, instead of that auto fb.button.

    I tried below, but it doesn’t logout me from facebook

    Test

    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
    });
    FB.Event.subscribe(‘auth.logout’, function(response) {

    });
    FB.logout(function(response) {

    });
    };
    (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);
    }());

    Please help me, any way to logout from FB

    • Awais Qarni December 28, 2010 at 5:36 pm #

      Replace the function FB.logout after (function) and call this function on any onclick event of button or anchor tag.

  157. Praveen Kumar December 29, 2010 at 12:10 pm #

    Thanks a lot for successful article.

    Please suggest a way to post on my friends wall.

    regards

  158. Alex Miller December 30, 2010 at 12:26 am #

    I copied your code and put in my App ID, and now I get this error:

    “Uncaught ReferenceError: FB is not defined”

    Any suggestions?

    • Alex Miller December 30, 2010 at 12:29 am #

      Looks like it works in Firefox, but not in Chrome.

  159. terano January 4, 2011 at 8:39 am #

    Hello
    Please is there any one who could manage media post along with your text.I’ve been using my API with the script that Mahmud skindly shared just wanted to post my photo,video and other material on facebook wall.

    Please any one can help?
    Thanks

  160. john andor January 4, 2011 at 2:10 pm #

    Your article is very informative and the use of graphics adds to understanding the process. I think some of your sentences are too long, and a few minor commas are missing. One thing I was taught, never end a sentence with a preposition.
    Custom Fan Page

  161. róbert January 10, 2011 at 5:25 am #

    hy,
    can someone give me an example about getting the selected friend id?
    thank you for the answer

  162. KTU January 11, 2011 at 6:54 am #

    This is really helpful.

    Thank you.

  163. Jey January 11, 2011 at 9:21 pm #

    Hi, great post about JS / GRAPH API
    I hav saw on the window opened by “Share With Your Friends” , there is possibility to switch “Send as a Message instead”. So we can send instant private message.
    Do you know how it’s possible to select this possibility by default?
    Tks a lot

    • mahmud ahsan January 13, 2011 at 1:52 am #

      As far as I know by default not possible. If you discover its possibility let me know then I’ll inform it my users.

  164. Pride Grimm January 16, 2011 at 9:32 pm #

    Hey, I am new to learning the FB api. I copied and pasted the full code and ran, everything works great except the legacy status post. It says it successfully posted, but it’s not on my FB wall. but when I ran your demo, it works fine. I’ve changed appid, I can’t really figure out what else would be different. Any ideas? I hope I’m not missing something real stupid.

  165. Friedrich Zohmann January 17, 2011 at 12:01 pm #

    Hi,

    Does anyon know if there is a replacement in the new Graph API for these calls from the old REST API:
    $facebook->api_client->users_isAppUser($user_id);
    $facebook->api_client->users_hasAppPermission(‘publish_stream’, $user_id);
    The 1st one checks if a user has authorized the APP and the 2nd one checks if the user already has authorized the “posting on wall” permission for the APP.
    I dont know how I can check that with the new PHP SDK.
    thanks, Friedrich