Learn More

Saturday, August 4, 2012

How To Use FB.api With Jquery

graph api explorer dashboard
As we mentioned earlier, that the social graph of Facebook is contained in a set of secure network, Graph API. There are many ways to access the Graph API, if you understand about accessing JSON with javascript, could certainly get the JSON objects easily. However, Facebook provides a function that is intended to get JSON objects from the Graph API. As we stated before, that blogger only support for Javascript, so we will only discuss FB.api Javascript combined with jquery. In general, the format FB.api is as follow


FB.api(path, method, params, cb);

Where
path : secure network url of Graph API
method : http method such as GET, POST, DELETE
params : paramters for query
cb         : callback function to handle response

FB.api function should be placed in the SDK Javascript functions which may result an access token. This means you can put FB.api inside FB.login, FB.getLoginStatus, Fb.getAuthResponse, FB.EventSubscribe. This is done because to access JSON of Graph API required an access token value. As we have stated before, the output of the Graph API is a JSON, meaning the output of the cb is JSON as well. The number of objects of Graph API JSON depends on the value of the access token and the user account settings.

Example to retrieving user profile
Suppose your name is Naitik Shah, and the output of Graph API is as follows

{
   "id": "5526183",
   "name": "Naitik Shah",
   "first_name": "Naitik",
   "last_name": "Shah",
   "link": "https://www.facebook.com/naitik",
   "username": "naitik",
   "gender": "male",
   "locale": "en_US"
}

Suppose you want to get the ID and Name, then FB.api is as follows

<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script type=”text/javascript”>
$(document).ready(function(){
            window.fbAsyncInit = function() {
                FB.init({
                        appId      : 'Your-App-Id',
                        status     : true, 
                        cookie     : true,
                        xfbml      : true,
                        oauth      : true,
                });
                FB.getLoginStatus(function(response) {
  if (response.status === 'connected') {
    // the user is logged in and has authenticated your
    // app, and response.authResponse supplies
    // the user's ID, a valid access token, a signed
    // request, and the time the access token 
    // and signed request each expire
    var uid = response.authResponse.userID;
    var accessToken = response.authResponse.accessToken;
    $(‘#loginfb’).css(‘display’,’none’);
    $(‘#logoutfb’).css(‘display’,’block’);
   getYourProfile(accessToken);
  } else if (response.status === 'not_authorized') {
    // the user is logged in to Facebook, 
    // but has not authenticated your app
    $(‘#loginfb’).css(‘display’,’block’);
    $(‘#logoutfb’).css(‘display’,’none’);
  } else {
    // the user isn't logged in to Facebook.
    $(‘#loginfb’).css(‘display’,’block’);
    $(‘#logoutfb’).css(‘display’,’none’);
  }
 });
$(‘#loginfb’).click(function(){
             FB.login(function(response) {
   if (response.authResponse) {
     console.log('Welcome!  Fetching your information.... ');
    var accessToken = response.authResponse.accessToken;
    getYourProfile(accessToken);    
   } else {
     console.log('User cancelled login or did not fully authorize.');
   }
 },{scope: 'email,user_likes'});
    });
   $('#logoutfb').click(function(){
FB.logout(function(response){
window.location = 'http://www.threelas.com/';
});
    });
   function getYourProfile(token){
FB.api(‘/me’, ’GET’, function(response){
var YourID = response.id;
var YourName = response.name;
document.getElementById(‘output’).innerHTML = “Your name is “ + YourName + “ and 
                                                    your ID is “ + YourID;
});
  }
            };

// Load the SDK Asynchronously
(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId= Your-App-Id ";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
});
</script>
<button id=”loginfb”>Login</button>
<button id=”logoutfb”>Logout</button>
<div id=”output”>Result</div>
</body>

In the above example the output of program is Your Name is Naitik Shah and your ID is 5526183. The problem is, how do we know the output of JSON? You can find out from Graph API Explorer. Also from the example, we don't use access token. Because ID and NAME is public. See the picture above, we don't need access token to get ID and NAME of Putri Arisnawati. To know more about how to use access token in FB.api we will discuss later. So wait for our next tutorial.

Post a Comment