SEO

September 18, 2010

Facebook is hard to 'LIKE' but this guy makes it easier

Some days ago facebook released their new graph api system to develop social sites more easily. Its really cool and I personally like the facebook's new graph api system. Facebook also updated their old facebook connect system and provided better way to integrate facebook connect feature, user authentication and calling facebook api from website.

In this article, I'll highlight javascript base

  1. Facebook connect authentication for websites
  2. How to use graph api
  3. How to show stream publish prompt and share prompt
  4. How to run FQL query using javascript
  5. How to set status using old legacy api calling by javascript

Here is the demo http://thinkdiff.net/demo/newfbconnect1/newconnect.php

fbconnect-demo

1. Facebook connect authentication

Firstly you've to setup a facebook application to get the application id. You can setup application from here. Or if you have already setup a facebook application then just copy the application id and replace with xxxxxxxxxxx.

01 <div id="fb-root"></div>
02 <script type="text/javascript">
03 window.fbAsyncInit = function() {
04 FB.init({appId: 'xxxxxxxxxxxxxx', status: true, cookie: true, xfbml: true});
05 };
06 (function() {
07 var e = document.createElement('script');
08 e.type = 'text/javascript';
09 e.src = document.location.protocol +
10 '//connect.facebook.net/en_US/all.js';
11 e.async = true;
12 document.getElementById('fb-root').appendChild(e);
13 }());

Just put this code in your html file after the body tag. This is the most efficient way to load the javascript SDK in your site. And in this way the sdk will load asynchronously so it does not block loading other elements of your page. Details of FB.init method.

And your html tag should be

1 <!DOCTYPE html>

Now we will use another method FB.Event.subscribe so that we can subscribe some events like login, logout, sessionChange. So modify the window.fbAsynInit and update by below code

01 window.fbAsyncInit = function() {
02 FB.init({appId: 'xxxxxxxxxxx', status: true, cookie: true, xfbml: true});
03  
04 /* All the events registered */
05 FB.Event.subscribe('auth.login', function(response) {
06 // do something with response
07 login();
08 });
09 FB.Event.subscribe('auth.logout', function(response) {
10 // do something with response
11 logout();
12 });
13  
14 FB.getLoginStatus(function(response) {
15 if (response.session) {
16 // logged in and connected user, someone you know
17 login();
18 }
19 });
20 };

 

So when user will login first time (not automatically) login() method will call. When user will click logout , logout() method will call. So define these functions for your application purpose. We also use another method FB.getLoginStatus() within window.fbAsyncInit() function so that when we found user is logged in or connected we will show some info to user.

Now we have to render fb connect button so that user can login or logout.

1 <fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button>

If you don't need any extended permissions from user then remove perms="email,user_birthday,status_update,publish_stream" this line. If you don't want to use standard fbconnect button for login and logout you can define your own connect button. Checkout FB.login for login javascript method and FB.logout for logout javascript method.

2. How to use graph api

To fully understand graph api visit the link . Now i'll show how you can use graph api using javascript sdk. There is a method FB.api . This method directly hooks graph api and returns result. Sample code

1 FB.api('/me', function(response) {
2 alert(response.name);
3 });

By calling this method it will show logged in user name.
In my demo you'll see another customized method graphStreamPublish(). This method uses FB.api() and does a HTTP POST request to http://graph.facebook.com/me/feed url with message parameter. So that the message will publish to users own wall.

01 function graphStreamPublish(){
02 var body = 'Reading New Graph api & Javascript Base FBConnect Tutorial';
03 FB.api('/me/feed', 'post', { message: body }, function(response) {
04 if (!response || response.error) {
05 alert('Error occured');
06 } else {
07 alert('Post ID: ' + response.id);
08 }
09 });
10 }

3. How to show stream publish prompt and share prompt

There is another javascript sdk method named FB.ui. Using the code you can prompt user for stream publish or share your page. Checkout streamPublish() and share() methods defination in my demo's source code .

4. How to run FQL query using javascript

Facebook Query Language enables you to use a SQL-style interface to query the data exposed by the Graph API. It provides for some advanced features not available in the Graph API, including batching multiple queries into a single call. Checkout the tables to know which data of facebook user you can retrieve. In the demo's source code you'll see

01 function fqlQuery(){
02 FB.api('/me', function(response) {
03 var query = FB.Data.query('select name, hometown_location, sex, pic_square from user where uid={0}', response.id);
04 query.wait(function(rows) {
05  
06 document.getElementById('name').innerHTML =
07 'Your name: ' + rows[0].name + "<br />" +
08 '<img src="' + rows[0].pic_square + '" alt="" />' + "<br />";
09 });
10 });
11 }

This method used the sdk method FB.Data.query to run FQL. Checkout the link for a complex query example.

5. How to set status using old legacy api calling by javascript

You can still call the old legacy api. In my demo you'll see a text box, write something and click 'Status Set Using Legacy Api Call' You'll see your facebook status will update.

01 function setStatus(){
02 status1 = document.getElementById('status').value;
03 FB.api(
04 {
05 method: 'status.set',
06 status: status1
07 },
08 function(response) {
09 if (response == 0){
10 alert('Your facebook status not updated. Give Status Update Permission.');
11 }
12 else{
13 alert('Your facebook status updated');
14 }
15 }
16 );
17 }

But remember to run successfully the demo, update status and publish stream using graph api you must approved all exteneded permissions those will show you during first access to the application.

Hope this article will help you to make facebook connected social site.

Here is my demo's full source code:

001 <!DOCTYPE html>
003 <head>
004 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
005 <title>New Graph api & Javascript Base FBConnect Tutorial | Thinkdiff.net</title>
006 </head>
007 <body>
008 <div id="fb-root"></div>
009 <script type="text/javascript">
010 window.fbAsyncInit = function() {
011 FB.init({appId: '113700398662301', status: true, cookie: true, xfbml: true});
012  
013 /* All the events registered */
014 FB.Event.subscribe('auth.login', function(response) {
015 // do something with response
016 login();
017 });
018 FB.Event.subscribe('auth.logout', function(response) {
019 // do something with response
020 logout();
021 });
022  
023 FB.getLoginStatus(function(response) {
024 if (response.session) {
025 // logged in and connected user, someone you know
026 login();
027 }
028 });
029 };
030 (function() {
031 var e = document.createElement('script');
032 e.type = 'text/javascript';
033 e.src = document.location.protocol +
034 '//connect.facebook.net/en_US/all.js';
035 e.async = true;
036 document.getElementById('fb-root').appendChild(e);
037 }());
038  
039 function login(){
040 FB.api('/me', function(response) {
041 document.getElementById('login').style.display = "block";
042 document.getElementById('login').innerHTML = response.name + " succsessfully logged in!";
043 });
044 }
045 function logout(){
046 document.getElementById('login').style.display = "none";
047 }
048  
049 //stream publish method
050 function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
051 FB.ui(
052 {
053 method: 'stream.publish',
054 message: '',
055 attachment: {
056 name: name,
057 caption: '',
058 description: (description),
059 href: hrefLink
060 },
061 action_links: [
062 { text: hrefTitle, href: hrefLink }
063 ],
064 user_prompt_message: userPrompt
065 },
066 function(response) {
067  
068 });
069  
070 }
071 function showStream(){
072 FB.api('/me', function(response) {
073 //console.log(response.id);
074 streamPublish(response.name, 'Thinkdiff.net contains geeky stuff', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
075 });
076 }
077  
078 function share(){
079 var share = {
080 method: 'stream.share',
082 };
083  
084 FB.ui(share, function(response) { console.log(response); });
085 }
086  
087 function graphStreamPublish(){
088 var body = 'Reading New Graph api & Javascript Base FBConnect Tutorial';
089 FB.api('/me/feed', 'post', { message: body }, function(response) {
090 if (!response || response.error) {
091 alert('Error occured');
092 } else {
093 alert('Post ID: ' + response.id);
094 &nbs
Po recommended