google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






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.


Label: JavaScript SDK Facebook, Facebook app SDK, JavaScript Facebook API, Facebook graph API, graph API Facebook

Generate your business videos by AI with voice or just text



Your first FREE AI Video App! Automate Your First AI Video. Create Your Professional Video In 5 Minutes By AI No Equipment Or Video Editing Skill Requred. Effortless Video Production For Content Marketers.
Free UNLMITED AI Video App in Your Hand

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.

AIVideo-App.com
Generate your business videos by AI with voice or just text

chatGPTaz.com
Talk to ChatGPT by your mother language

AppAIVideo
Your first FREE AI Video App

Deepfake Video
Deepfake AI Video Maker

Deepfake
Deepfake AI Video Maker

AI Deep Fake
Deepfake AI Video Maker

AIvidio
AI Video Mobile Solutions

AIvideos
AI Video Platform & Solutions

AIvedio
AI Video App Maker

Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)

Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)

Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE

Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE

Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE

Powerful AI Presentation PPT Maker for FREE
Build an impressive presentation with our free online AI presentation app

Your next top AI Assistant
Claude AI, developed by Anthropic

Your next top AI Assistant
Claude AI, developed by Anthropic

Temu Free $500 for New Users
Claim Free Temu $500 Credit via Affiliate & Influencer Program

Free TikTok Ads Credit
Master TikTok Ads for Your Business Marketing

Dall-E-OpenAI.com
Generate creative images automatically with AI

chatGPT4.win
Talk to ChatGPT by your mother language

First AI Product from Elon Musk - Grok/UN.com
Speak to Grok AI Chatbot with Your Language

Tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

iPhoneKer.com
Save up to 630$ when buy new iPhone 16

Buy Tesla Optimus Robot
Order Your Tesla Bot: Optimus Gen 2 Robot Today for less than $20k

JavaScript by day


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web