Categories
Javascript

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 😀 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: 'https://masnun.com/'
 };

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

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

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

12 replies on “Using The Facebook Graph API with js-sdk : An explanatory Tutorial”

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?

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.

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.

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?

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!”
}
}
});

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.

I am struggling hard to add bookmark and like buttons in iframe for an game application. I searched multiple tutorial. Most of outdated. I am totally confused of how to go further. Can you guide me in this?

Hello Masnun, kindly help…My app is very simple 3 page html application
1) Landing canvas page where user clicks go to app resulting into oauth dialog asking for permissions
2) Input form where in user selects one option and submits form
3) result page where there is a picture which I want to tag/post on users wall/album.
I know how to load JS api in the first page, I can go thru the oauth and get the token in the url

But how to use this token on second page and the same on third page. And how to tag/upload pic to user’s profile
Please help

Please look at the Facebook documentation for uploading photos.

Regarding the oAuth token, you should use it to construct the facebook object in the next page. I haven’t worked on the FB APIs for a long time now, don’t remember things well. 🙁

Comments are closed.