JavaScript Experiments of Facebook SDK with Graph API

This JavaScript article tutorial provide us many helpful experiences to develop Facebook applications with JavaScript API. Besides, this JavaScript article tutorial also guides you how to build a simple JavaScript application to get feeds. Please go to the full post page for details.


Sampled by © JavaScriptBank.com

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.

Part II

Here goes the link of the first part. In this post I will share (or better to say note down about further experience in FB Javascript API).

Here I will try to focus on :::

(2) get fans count and their feed on page's wall to promote and to share the page.

(3) post to wall (to my page or profile) from my site.

Steps for task (2) :

[1] Facebook fan pages are awesome tools for marketing or promotion. They are attached to facebook open graph. SO it is very much easy to access their public info like feed stream and fan count. But for the other info there should be nneded to logging in.

[2] If we hit to https://graph.facebook.com/ we will get all the public info like -- id, name, username(if any), page profile picture, link, location, hours open. For other info we have to use metdata tag. for this purpose we may hit https://graph.facebook.com/?metadata=1. We may find links for feed, posts, tagged, statuses, links, notes, photos, albums, events and videos. Among them feed, posts, photos and albums are publicly accessible.

[3] So using this protocol we can find and fulfil our needs as mentioned above.

[4] We have called javascript api for getting fancount and for feeds we have used php as this is easy to maintain a multilevel data structure like array in php than javascript.

[5] So the frame of our code goes like as below :

<!doctype html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

  </head>
  <body>
    <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">
            $(document).ready(function(){
                FB.init({ apiKey: 'XXXXXXXXXXXXXXXXXXX' });
            });
    </script>
 </body>
</html>

[6] Here the FB.init is used to initiate the api call. Now to get the fan count we will add the following function after document.ready block and call the function from document.ready.

function getUpdate () {
var htmls = '<div style="background-color:#77A1CD:color:#EAAA00;">';

FB.api('/224365082363', function(response1) {
                        total_members = response1.fan_count;
                        name = response1.name;
                        link = response1.link;
                        htmls += 'Total <i>'+total_members+'</i> persons likes '+'<a href="'+link+'">'+name+'</a><br>';
                        htmls += '</div>';
                        $('#user-info').show();
                        $('#user-info').attr("style","width:450px;height:auto;background-color:#E4E9EE");
                        $('#user-info').html(htmls);
               });
}


[7] Now to find the lates feeds we have used php. From php we have called the same graph protocol and used file_get_contents. the returned datatype is json. SO we used json_decode to parse the data. Then the data type becomes an stdclassobject. The code goes as follows:

<?php
 $myObj = json_decode(file_get_contents("https://graph.facebook.com/224365082363/feed"));
echo "<br>";
$i = 0;
        foreach ($myObj->data as $aData){
                $user[$i]['from'] = $from = "<a href=\"http://www.facebook.com/profile.php?id=".$aData->from->id."\" >".$aData->from->name."</a>";
                $user[$i]['msg'] = $message = $aData->message;
                $created = $aData->created_time;
                
                
                $html  = "<div style=\"background-color:#F9F9F9;color:#000000;height:auto;width:500px;\">";
                $html .= $from.": ".$message;
                $html .= "<font size=\"1\">   ".$created."</font>";
                $html .= "<hr style=\"border-style:dotted; border-color:#6D84B4\"/>";
                $html .= "</div>";
                echo $html;
                $i++;
        }
?> 

[8] Here the time returned is on 'yyyy-mm-ddThh:mm:ss' format but normally and specially our application demands time difference from now liek as how many mniutes ago the feed was posted. So for these reason we have used a function that calculates the time difference in days, hours and miniutes. the code block for the function and the calling will be as follows:

<?php
 $myObj = json_decode(file_get_contents("https://graph.facebook.com/224365082363/feed"));
echo "<br>";
$i = 0;
        foreach ($myObj->data as $aData){
                $user[$i]['from'] = $from = "<a href=\"http://www.facebook.com/profile.php?id=".$aData->from->id."\" >".$aData->from->name."</a>";
                $user[$i]['msg'] = $message = $aData->message;
                $created = $aData->created_time;
                $createdtime = date('Y-m-d h:i:s', strtotime($created));
                $now = date('Y-m-d h:i:s', time());
                $user[$i]['ago'] = $difference = get_time_difference($createdtime, $now);
                
                $html  = "<div style=\"background-color:#F9F9F9;color:#000000;height:auto;width:500px;\">";
                $html .= $from.": ".$message;
                $html .= "<font size=\"1\">   ".$created."</font>";
                $html .= "<hr style=\"border-style:dotted; border-color:#6D84B4\"/>";
                $html .= "</div>";
                echo $html;
                $i++;
        }

function get_time_difference($start, $end){

        $tempstart1 = explode('-',$start);
        $startyr = $tempstart1[0];
        $startmon = $tempstart1[1];
        $tempstart2 = explode(' ',$tempstart1[2]);
        $startday = $tempstart2[0];
        $tempstart3 = explode(':',$tempstart2[1]);
        $starthr = $tempstart3[0];
        $startmin = $tempstart3[1];
        $startsec = $tempstart3[2];

        $tempend1 = explode('-',$end);
        $endyr = $tempend1[0];
        $endmon = $tempend1[1];
        $tempend2 = explode(' ',$tempend1[2]);
        $endday = $tempend2[0];
        $tempend3 = explode(':',$tempend2[1]);
        $endhr = $tempend3[0];
        $endmin = $tempend3[1];
        $endsec = $tempend3[2];
        

        $start1 = mktime($starthr, $startmin, $startsec, $startmon, $startday, $startyr);
        $end1 = mktime($endhr, $endmin, $endsec, $endmon, $endday, $endyr);

        $dateDiff = $end1 - $start1;
        $fullDays = floor($dateDiff/(60*60*24));
        $fullHours = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
        $fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
        
        $ret = "";
        if($fullDays > 0){
                $ret .= "$fullDays Days ";
        }
        if($fullHours > 0){
                $ret .= "$fullHours Hours ";
        }
        if($fullMinutes > 0){
                $ret .= "$fullMinutes Minutes ";
        }

        if($ret!= ''){
                $ret .= "ago";
        } else {
                $ret .= "A Few Moments ago";
        }

        return $ret;
}
?> 

[9] so the final out put will be as the following screenshot -


So we will be back soon with posting to wall steps. ;-)

Language
Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
Insights for Advanced Zooming and Panning in JavaScript Charts
How to open a car sharing service
Vue developer as a vital part of every software team
Vue.js developers: hire them, use them and get ahead of the competition
3 Reasons Why Java is so Popular
Migrate to Angular: why and how you should do it
The Possible Working Methods of Python Ideology
JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
Learning How to Make Use of New Marketing Trends
5 Important Elements of an E-commerce Website


Top view articles
Adding JavaScript to WordPress Effectively with JavaScript Localization feature
Top 10 Beautiful Christmas Countdown Timers
Top 10 Best JavaScript eBooks that Beginners should Learn
65 Free JavaScript Photo Gallery Solutions
16 Free Code Syntax Highlighters by Javascript For Better Programming
Best Free Linux Web Programming Editors
Top 50 Most Addictive and Popular Facebook mini games
More 30 Excellent JavaScript/AJAX based Photo Galleries to Boost your Sites
Top 10 Free Web Chat box Plug-ins and Add-ons
The Ultimate JavaScript Tutorial in Web Design


Free JavaScript Tutorials & Articles
at www.JavaScriptBank.com