Chris Tankersley

Building Facebook Apps - The JavaScript SDK

Posted on 2011-08-12

In our first part of these tutorials, we added our application to Facebook. The reason that we do this is so that Facebook will allow our application to not only be useable on their platform, but to allow our application to use data stored in Facebook. Before we dive into server-side development, let's take a look at the client-side platform - the JavaScript SDK.

Parts of the JavaScript API

There are three parts to using the JavaScript API. You have the JavaScript that Facebook makes available to everyone and wraps their services into useable functions, the 'fb-root' div which must be on each page the API is included on, and then your own code which initializes Facebook. These are the building blocks for using the API.

Before we get to writing any code, head back into the Facebook Developer App and find your App ID. Keep that handy as we'll need it in just a moment. We don't need to worry about the Application Secret at this point.

To get us started, open up your page and drop in the following:

<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.init({
    appId: '<Your App ID>',
    status: true,
    cookie: true,
    oauth: true
});
</script>

This creates the bare necessities for creating a Facebook JavaScript app, and connects your app to Facebook.

Checking to see if the User is Logged In

Connecting to Facebook itself really doesn't do much, but it does expose a lot of functionality to us. To get access to the user information, we need to check to see if the user is connected to Facebook and has allowed our application. For privacy reasons every application must request access to user data, just like the Developer App requested for information access when we added it.

The API exposes a FB.getLoginStatus() function that will check to see if the user is logged in and connected to the application. It takes a callback function that will be fired once the response comes back from Facebook. Let's plug that in:

FB.getLoginStatus(function(stsResp) {
    if(stsResp.authResponse) {
        // We're logged in and ready to go!
    } else {
        // We're not connected
    }
});

Pretty basic. If the user is connected, we'll get an authResponse back. If there isn't one, we need to connect. For that we have the FB.login() function. It prompts the user to authorize the application and then executes some code via a callback. So let's expand the code a bit. If the user is connected, fetch their info. If they aren't connected, request the login and then fetch their info:

FB.getLoginStatus(function(stsResp) {
    if(stsResp.authResponse) {
        getUserInfo();
    } else {
        FB.login(function(loginResp) {
            if(loginResp.authResponse) {
                getUserInfo();
            } else {
                alert('Please authorize this application to use it!');
            }
        });
    }
});

If the user cancels the login process we'll give them an alert saying they need to authorize the app. If everything goes according to plan, we'll call getUserInfo(), which is a function we'll build to get the user's info.

The Graph API

The whole point of Facebook is what is known as a Social Graph. In short, this is a mapping of everyone and how they are connected. Facebook takes the Social Graph and has built an API on top of it, naming this API the Graph API. Through the Graph API we can view and make changes to someone's social graph.

To see what this looks like, head over to Facebook's Graph API Explorer. This is a GUI front-end for viewing the Graph API. For a quick test, enter in your Facebook username and click 'Submit'. You should get some JSON back with your ID, name, and other information.

In the JavaScript SDK, this process is exposed via the FB.api() function. It takes a path in the API, and a function as a callback. It's define 'getUserInfo()' to do this:

var userData = null;

function getUserInfo() {
    FB.api('/me', function(resp) {
        userData = resp;
    });
}

This gets the user information for the currently logged in user and stores it as a global variable for our JavaScript to use in a few moments. Since we authorized the application earlier, we gain access to a wealth of user information right away. Not only do we get the ID, name, etc, from earlier but we now get Hometown, Location, and Education. We can ask for more with extended permissions, but for now we have enough information.

To The Wall!

Everyone loves to see the stuff that their friends post on their walls. So let's have our app do the same. Let's allow the user to submit their home town to our app and then allow them to post something to their wall to let their friends know they've done the same. I'll use jQuery to do the posting via AJAX.

To get the prompt, we utilize the FB.ui() function. This function exposes things like the Wall Post dialog we'll be using, sending app requests to friends, and many other things that require a pop-up. This takes an object of options for the method, and a callback to do something.

The parameter for the callback can be used to detect whether or not the user actually went through the action. Since I'm not interested in that, we'll just always send an alert of 'Thansk!' whether or not the user posted to the wall.

// We have a link somewhere above that looks like:
// <a href="#" id="sendHometownLink">Submit Your Home Town!</a>
$('#sendHometownLink').click(function() {
    $.ajax({
        data: {
            'hometownID': userData.hometown.id, 
            'hometownName': userData.hometown.name,
            'userID': userData.id
        },
        dataType: 'json',
        success: function(data) {
            postToWall();
        },
        type: 'POST',
        url: '/addhometown.php'
    });
    return false;
});

function postToWall() {
    FB.ui({
        method: 'stream.publish',
        message: 'I added my hometown, so should you!',
        attachment: {
            name: 'Hometown Collector Sample App',
            caption: 'We promise not to do anything bad with it',
            href: 'http://www.ctankersley.com'
        },
        user_prompt_message: ''
    }, function(resp) {
        alert('Thanks!');
        return true;
    });
}

From Here

This is a fully functional app. From here you can build something that analyzes the home towns of people, makes funny jokes from that, or whatever. The main functions above are the building blocks for an application, and will get you well on your way to creating a more function-heavy Facebook application. Throw in your own JavaScript framework like jQuery to add in all the functionality you would get from a normal web application.


Comments