May 11, 2010

Experiencing Facebook Javascript SDK with graph API - I

This is the first time I am using Facebook Javascript API. In fact this is the first time I am using any facebook api. So I am excited to some extend. I have heard that the api and documentations are easy enough to understand. I read the facebook release of graph api and f8 and they looked coooooool to work with.

The basic purpose of my work was three things -
(1) Get Home page feeds and present them as scrolling in my site
(2) create custom buttons with friends and/or fans count to promote
(3) post to wall (to my page or profile) from my site.

To the experts these are definitely piece-of-cake but for a first timer like me they are the basic things to work with.

So in this post I will discuss  how i learned to get the home page feeds.

Steps for (1) Get Home page feeds and present them as scrolling in my site:

[a] I have created an canvas application called testfbapp (this is just to get an api key) from http://developers.facebook.com/setup . I have set my site name as testfbapp and my site url as http://localhost/testfbapp (as i am planning to test my codes on localhost).

[b] Now from the next page that comes after creating the application I have clicked the developer dashboard link. There all the application that just have been created will be shown. I have copied the API Key, the secret key and the application ID for the app and kept that somewhere.

[c] Then I have searched for Javascript SDK and found it on http://github.com/facebook/connect-js/ . I have downloaded the sdk and copied that to my local directory which is testfbapp under my web root.


[d] In order to get used to it i have roamed around the files I have downloaded and found that it the sdk supports a lot variety of popular javascript libraries like dojo, jquery, mootools, prototype, yui2. Because of previous little experience in jquery I have chosen that.

[e] Now I have created a file named index.php at the project root. I have copied contents from the login.html from examples/jquery directory and pasted it into the index.php page.

[f] Then I have removed the contents of handleSessionResponse() after the following code block

if (!response.session) {
          clearDisplay();
          return;
        }

So the page looks like as follows:
<!doctype html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  </head>
  <body>
    <div>
      <button id="login">Login</button>
      <button id="logout">Logout</button>
      <button id="disconnect">Disconnect</button>
    </div>
    <div id="user-info" style="display: none;"></div>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

    <div id="fb-root"></div>
    <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>

    <script type="text/javascript">
      // initialize the library with the API key
      FB.init({ apiKey: '.....' });

      // fetch the status on load
      FB.getLoginStatus(handleSessionResponse);

      $('#login').bind('click', function() {
        FB.login(handleSessionResponse);
      });

      $('#logout').bind('click', function() {
        FB.logout(handleSessionResponse);
      });

      $('#disconnect').bind('click', function() {
        FB.api({ method: 'Auth.revokeAuthorization' }, function(response) {
          clearDisplay();
        });
      });

      // no user, clear display
      function clearDisplay() {
        $('#user-info').hide('fast');
      }

      // handle a session response from any of the auth related calls
      function handleSessionResponse(response) {
        // if we dont have a session, just hide the user info
        if (!response.session) {
          clearDisplay();
          return;
        }
      }
    </script>
  </body>
</html>

[g] Now I have read about the graph api of facebook from http://developers.facebook.com/docs/api and for our purpose (i.e. to get home page feeds) I found that
https://graph.facebook.com/user-name/home link is helpful. So I have tested on the browser address bar putting my FB user name and some of my friends FB user name and found that it works only for current user that the logged in user. but https://graph.facebook.com/user-name works for self and friends information. It fetches only publicly viwable information. So our next step should bego through the javascript api reference to utilize the graph api.

[h] I have gone through http://developers.facebook.com/docs/reference/javascript and found that FB.api  API call is the right method to use as it can directly call to graph API.

[i] I have put my API key for my application in the FB.init() method and following this guide I have written the following code in the handleSessionResponse() method. I have checked https://graph.facebook.com/user-name?metadata=1 url in my browser to find the proper link for home feeds. I have used

for(property in response){
   alert(property);
}

to check the properties of the response object. And then for output I have written --

var user_id = FB.getSession().uid;
FB.api('/'+user_id+'/home', function(response) {
  var total_feed = response.data.length;
   var htmls = '<ul style="list-style-image: none; list-style-position: outside; list-style-type: none;">';       
 for(var x = 0; x < total_feed; x++) {       
  name = response.data[x].from.name;       
  id = response.data[x].from.id;       
  message = response.data[x].message;       
  created_time = response.data[x].created_time;              
  htmls += ""; 
  htmls += '<a href="http://www.facebook.com/profile .php ?id='+id+'>'+  name+'</a>:';
  htmls += message;
  htmls += " created at ::: "+created_time+""; 
 htmls += "";   
}      
htmls += "</ul>";
  $('#user-info').show();
  $('#user-info').attr("style","width:450px;height:auto;background-color:#E4E9EE");
  $('#user-info').html(htmls);
});


[j] Here FB.getSession() holds all the session variables after authentication. If some user visiting my page is not logged in the FB.getSession() is null and it will not return any feed. To login there is a login button at the top of the page (at the top of my code). After clicking that button there will be an iFrame dialogue box appeared and will ask permission from the user to login and then to allow the application to fetch  profile data.

[k] Now if we run http://localhost/testfbapp and login using FB credential and allow this application we will see the recent homepage feeds.

[l] Now to automate this script that is to get live updates we may modify the codes like as follows and this is our final version of this code.

<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  </head>
  <body>
    <div>
      <button id="login">Login</button>
      <button id="logout">Logout</button>
      <button id="disconnect">Disconnect</button>
    </div>
    <div id="user-info" style="display: none;"></div>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

    <div id="fb-root"></div>
    <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>

    <script type="text/javascript">
      // initialize the library with the API key
      FB.init({ apiKey: 'XXXXXXXXXXXX' });

      // fetch the status on load
      FB.getLoginStatus(handleSessionResponse);

      $('#login').bind('click', function() {
        FB.login(handleSessionResponse);
      });

      $('#logout').bind('click', function() {
        FB.logout(handleSessionResponse);
      });

      $('#disconnect').bind('click', function() {
        FB.api({ method: 'Auth.revokeAuthorization' }, function(response) {
          clearDisplay();
        });
      });

      // no user, clear display
      function clearDisplay() {
        $('#user-info').hide('fast');
      }

      // handle a session response from any of the auth related calls
      function handleSessionResponse(response) {
        // if we dont have a session, just hide the user info
        if (!response.session) {
          clearDisplay();
          return;

        var user_id = FB.getSession().uid;
        var access_token = FB.getSession().access_token;

        getUpdate();

      }

      function getUpdate () {
              var user_id = FB.getSession().uid;
              //alert(user_id);
              var access_token = FB.getSession().access_token;
              //alert(access_token);
              FB.api('/'+user_id+'/friends', function(response) {
                 var total_friend = response.data.length;
                 //alert(total_friend);

              });
              FB.api('/'+user_id+'/home', function(response) {
                        var total_feed = response.data.length;
                        var htmls = '<ul style="list-style-image: none; list-style-position: outside; list-style-type: none;">';                         
for(var x = 0; x < total_feed; x++) {        
name = response.data[x].from.name;        
id = response.data[x].from.id;        
message = response.data[x].message;        
created_time = response.data[x].created_time;               
htmls += "";  htmls += '<a href="http://www.facebook.com/profile .php ?id='+id+'>'+ name+'</a>:';
htmls += message;
htmls += " created at ::: "+created_time+""; 
htmls += "";   
}
                        htmls += "";
                        $('#user-info').show();
                        $('#user-info').attr("style","width:450px;height:auto;background-color:#E4E9EE");
                        $('#user-info').html(htmls);
                });
               

                t = setTimeout(getUpdate,15000);
        }

        

     </script>
  </body>
</html> 


Now this will be the ned of part 1 getting FB homepage feed.
[cont...]

7 comments :

  1. that's all cool & great fb tips, thank you very much for sharing.

    Can you give me favor to share this post on my JavaScript library?


    Awaiting your response. Thank

    ReplyDelete
  2. good work. Thanks. :)

    ReplyDelete
  3. Nag Baba darun likecho.... as expected ;)

    Keep it up buddy.

    Please correct last line typo mistake... (Now this will be the ned of part 1 getting FB homepage feed.)

    - Morshed

    ReplyDelete
  4. This post is great. Thank you for this post. I like this type of people who share knowledge with others.

    ReplyDelete
  5. It is the nice post one and thing are so good.Each and every content shows how this blogs .Thanks for making this wonderful site.

    ReplyDelete

Find Me Here

Himel Nag Rana's Facebook Profile

Hire Me

I Read Them

Popular Posts

... Inverting Things ... © 2013 Supported by Best Blogger Templates and Premium Blog Templates - Web Design