Learn More

Friday, August 17, 2012

How To Get Actions Of Facebook Open Graph With Jquery

open graph dashboard
This topic aims to explain how to get several actions. And this topic is a continuation of the previous topic, I have discussed how to create an Object Page, then how to setting up action-object. I also have discussed how to use FB.api, and how to make facebook login. Those topics very good to help you in learning this topic.

As I explain earlier, I just discussing with Javascript SDK FB.api combined with jquery. To be easy to learn, I have created a facebook application read-type article. Please log in to our request to be a tester https://www.facebook.com/Threelas facebook application.


How to Get Action
In general, to get a set of actions from Facebook users, you must include an access token. So that the function to get the actions should be put in the FB.login or FB.getLoginStatus or FB.EventSubscribe functions. Consider the following javascript code.

<html xmlns:fb="https://www.facebook.com/2008/fbml"> 
<head prefix="og: http://ogp.me/ns# [YOUR_APP_NAMESPACE]: 
                  http://ogp.me/ns/apps/[YOUR_APP_NAMESPACE]#">
  <title>OG Tutorial App</title>
  <meta property="fb:app_id" content="[YOUR_APP_ID]" /> 
  <meta property="og:type" content="[YOUR_APP_NAMESPACE]:recite" /> 
  <meta property="og:title" content="Stuffed Cookies" /> 
  <meta property="og:image" content="http://fbwerks.com:8000/zhen/cookie.jpg" /> 
  <meta property="og:description" content="The Turducken of Cookies" /> 
  <meta property="og:url" content="http://fbwerks.com:8000/zhen/cookie.html">
<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’);
   getActions(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;
    getActions(accessToken);    
   } else {
     console.log('User cancelled login or did not fully authorize.');
   }
 },{scope: 'email,user_likes',’publish_stream’});
    });
   $('#logoutfb').click(function(){
FB.logout(function(response){
window.location = 'http://www.threelas.com/';
});
    });
   function getActions (token){
                var article_url = new Array();
                var article_title = new Array();
var html = “”;
FB.api(‘/me/[YOUR_APP_NAMESPACE]:cook?access_token=’+token, ‘get’, function(response){
html += ‘<ul>’;
for(var i = 0; i < response.data.length; i++){
article_title[i] = response.data[i].data.post.title;
article_url[i] = response.data[i].data.post.url;
html += ‘<li>’+’<a href =”’+article_url[i]+’” target=”_blank”>’+article_title[i]+’</a></li>’;
}
html += ‘</ul>’;
document.getElementById(‘output’).innerHTML = html;
});
  }
            };

// 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>

The output of this program is a set of complete title of the article with the link. I have to remind you again, to check the JSON output of me/[YOUR_APP_NAMESPACE]:cook through the Graph API Explorer. This is done to be able to access objects of JSON properly.

Meanwhile if you use the read-article as built-in actions, the following are examples of how to access the JSON output actions.

<html xmlns:fb="https://www.facebook.com/2008/fbml"> 
<head prefix='og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# article: http://ogp.me/ns/article#'>
  <title>OG Tutorial App</title>
  <meta property="fb:app_id" content="[YOUR_APP_ID]" /> 
<meta content='article' property='og:type'/>
  <meta property="og:title" content="Stuffed Cookies" /> 
  <meta property="og:image" content="http://fbwerks.com:8000/zhen/cookie.jpg" /> 
  <meta property="og:description" content="The Turducken of Cookies" /> 
  <meta property="og:url" content="http://fbwerks.com:8000/zhen/cookie.html">
<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’);
   getActions(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;
    getActions(accessToken);    
   } else {
     console.log('User cancelled login or did not fully authorize.');
   }
 },{scope: 'email,user_likes',’publish_stream’});
    });
   $('#logoutfb').click(function(){
FB.logout(function(response){
window.location = 'http://www.threelas.com/';
});
    });
   function getActions (token){
                var article_url = new Array();
                var article_title = new Array();
var html = “”;
FB.api('/me/news.reads?access_token='+token, 'get', function(response){
html += ‘<ul>’;
for(var i = 0; i < response.data.length; i++){
article_title[i] = response.data[i].data.post.title;
html += ‘<li>’+’<a href =”’ +response.data[i].data.article.url+’” target=”_blank”>’+response.data[i].data.article.title+’</a></li>’;
}
html += ‘</ul>’;
document.getElementById(‘output’).innerHTML = html;
});
  }
            };

// 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>

Ok, you have read how to get actions with jquery. Wait our tutorial to learn how to publish an actions.

  1. Hi nice post, indeed. However, on blogger, as an instance, it will be too heavy to add the javascript code right on the template, as it will surely take more and more time to load. It is better to save the code on a js file and upload and host it somewhere to save the space and time load.
    Anyway thanks a bunch for stopping by at buka-rahasia.blogspot.com, I really appreciate it :)

    ReplyDelete
  2. Ya, I know about that, the aim of this tutorial is to give description how to merge blogger with facebook. So I give example code as practice

    ReplyDelete