Using The Facebook Graph API with js-sdk : An explanatory Tutorial

The facebook Graph API has a nice Javascript SDK to build applications using JS. The most important benefit is that with JS you could tightly integrate the Facebook Graph API with your web application.

Integration is quite easy. First we add a fbAsyncInit object to the window object for asynchronous initiating. The following code snippet was borrowed from the official docs and then slightly modified:

 
            window.fbAsyncInit = function() {
                FB.init({appId: appId, 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() {
           alert('login');
           }
 
           function logout() {
           alert('logout');
           }

Thanks to the elegance of Javascript, we called the newly constructed object immediately after initiating, with a callback that loaded the JS sdk on our page. We registered the auth.login, auth.logout events and for initially looking for any logged in user, we made the getLoginStatus() call. In fact this code snippet initiates the facebook access on the page. Registering the events to our custom functions, we just made sure that, we know when something important happens. While iniating, if the user is already logged in, the login() function gets called because of the getLoginStatus() call. Later, after initiating, if the user logs in or logs out, the auth.login and auth.logout events get fired. Our registered handlers will be called in those cases.

To make things easy for the end user, you can use a fb:login-button tag from FBML. I believe Facebook app developers are already aware of that. Still, I was just reminding that you can still use those tags :D A login button is going to help you. Because, it’s mandatory that you call the FB.login() on an user event (like button click) because most browsers won’t allow opening a popup on a non-user event.

Now the user is logged in and authorized the apps, you can start customizing your contents for the user. You can always check for available users by calling the FB.getSession() function. It returns null if no user is available, otherwise, it returns a session object with access_token, app key and secret and most importantly the user uid.

session = FB.getSession()
if(session) {
    alert(session.uid);
        } else {
     alert('no user logged in');
}

You can use the dir() function on the session object to explore it on the Firebug console.

Now, you can make calls to the Graph API using the normal path pattern:

FB.api("/me/photos", function(response) { alert(response.data[0].link) });

The above code will alert() the user’s latest photo URI. Well, make sure that the applicaton has permissions to make the calls.

You can even mix up with the legacy API by passing an object with a “method” parameter pointing to the method name and related args. You can build the Facbook UIs using the FB.ui() call. Have a look how we use legacy API and UI to build a nifty sharing dialog box.

var share = {
   method: 'stream.share',
   u: 'http://masnun.com/'
 };
 
 FB.ui(share, function(response) { console.log(response); });

Here, instead of alert()ing the response, we logged it to the console :D

In this way, you can interact with the user the way you want. It’s plain and simple. So, start digging now and have fun.

The Offcial js-sdk docs can be found here: http://developers.facebook.com/docs/reference/javascript/

Happy developing! Happy Facebooking! :D :D :D

This entry was posted in Blog Post and tagged , . Bookmark the permalink.

9 Responses to Using The Facebook Graph API with js-sdk : An explanatory Tutorial

  1. SHAHEE MIRZA says:

    কিছুই বুঝি নাই। এইটা কি হইলো? Facebook কি নতুন কিছু পাব্লিশ করছে নাকি!

  2. masnun says:

    হ্যা । নতুন এপিআই :)

    এইটা আগেরটার চেয়ে অনেক ভাল। অনেক অনেক :D

  3. Sammy says:

    I am new to FB development. Trying to use your code. FB Button is not visible by tag.
    Any ideas?
    Also, can you share entire sample code in single html page?

  4. David Leach says:

    I have a general question about using javascript and FB.api. I’m new to javascript so these may be stupid questions. I’ve been trying to get a handle on how to use these APIs but the documentation and examples are lacking.

    1) Is the only way to interact with FB.api is through the callback function? For example, are you not able to do: variable = FB.api()?

    2) If I want to do a series of FB.api calls to build up a table of information, how would one go about doing this without nesting the calls inside of the callback functions?

    3) Where do you find documentation on the structures for photo albums and photos etc… . I can see what they are via php.

  5. masnun says:

    I got the information from the Facebook Developers Wiki. I recommend you to look up in there. I worked with the JS APIs a long time ago and forgot much of this since then.

  6. Mits says:

    What parameters is one supposed to pass with the js-sdk to call a php script that will do some jobs on the server?

    For example i want someone to click on an image on my index page (that has loaded the js api) and when clicked i want to do an ajax call with php to write to my database that the user with this uid clicked that picture.

    should i pass the session parameter?

  7. masnun says:

    Yes. You have to pass the sessions.

  8. Mits says:

    Well !!!! There is someone who looks after his blog!!
    The fastest response i ever got on a blog!
    Could you provide some help? I have the following javascript code on my index and i want to call my PHP that implements the latest php api…what should i put inside the data?

    $.ajax({
    type: “POST”,
    url: “/tagPhoto.php”,
    data : “??????????????????????????”,
    success: function(msg){
    if(msg==”1″) {
    document.getElementById(‘result’).innerHTML=”Photo Tagged!”
    }
    }
    });

  9. masnun says:

    I worked with the Facebook APIs a long time ago. I think the php-sdk has auto login feature. If you can activate that, you might not require to pass anything. It’ll auto detect from cookies. I believe AJAX calls send cookies as well.

    Again, I don’t know much about JS. Correct me if I am wrong.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">