Thursday, April 28, 2011

Graph api & javascript base Facebook Connect tutorial

facebook-social 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
02
03
04
05
06
07
08
09
10
11
12
13
<div id="fb-root"></div>
<script type="text/javascript">
    window.fbAsyncInit = function() {
        FB.init({appId: 'xxxxxxxxxxxxxx', status: true, cookie: true, xfbml: true});
    };
    (function() {
        var e = document.createElement('script');
        e.type = 'text/javascript';
        e.src = document.location.protocol +
            '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
    }());
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 web host. 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
2
<!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
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
window.fbAsyncInit = function() {
 FB.init({appId: 'xxxxxxxxxxx', status: true, cookie: true, xfbml: true});
     /* All the events registered */
     FB.Event.subscribe('auth.login', function(response) {
         // do something with response
         login();
     });
     FB.Event.subscribe('auth.logout', function(response) {
         // do something with response
         logout();
     });
     FB.getLoginStatus(function(response) {
         if (response.session) {
             // logged in and connected user, someone you know
             login();
         }
     });
 };
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
2
3
FB.api('/me', function(response) {
  alert(response.name);
});
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
02
03
04
05
06
07
08
09
10
function graphStreamPublish(){
       var body = 'Reading New Graph api & Javascript Base FBConnect Tutorial';
        FB.api('/me/feed', 'post', { message: body }, function(response) {
            if (!response || response.error) {
                 alert('Error occured');
            } else {
                 alert('Post ID: ' + response.id);
            }
       });
 }
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
02
03
04
05
06
07
08
09
10
11
function fqlQuery(){
                FB.api('/me', function(response) {
                     var query = FB.Data.query('select name, hometown_location, sex, pic_square from user where uid={0}', response.id);
                     query.wait(function(rows) {
                       document.getElementById('name').innerHTML =
                         'Your name: ' + rows[0].name + "<br />" +
                         '<img src="' + rows[0].pic_square + '" alt="" />' + "<br />";
                     });
                });
            }
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
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
function setStatus(){
                status1 = document.getElementById('status').value;
                FB.api(
                  {
                    method: 'status.set',
                    status: status1
                  },
                  function(response) {
                    if (response == 0){
                        alert('Your facebook status not updated. Give Status Update Permission.');
                    }
                    else{
                        alert('Your facebook status updated');
                    }
                  }
                );
            }
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
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
<!DOCTYPE html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>New Graph api & Javascript Base FBConnect Tutorial | Thinkdiff.net</title>
    </head>
    <body>
        <div id="fb-root"></div>
        <script type="text/javascript">
            window.fbAsyncInit = function() {
                FB.init({appId: '113700398662301', status: true, cookie: true, xfbml: true});
                /* All the events registered */
                FB.Event.subscribe('auth.login', function(response) {
                    // do something with response
                    login();
                });
                FB.Event.subscribe('auth.logout', function(response) {
                    // do something with response
                    logout();
                });
                FB.getLoginStatus(function(response) {
                    if (response.session) {
                        // logged in and connected user, someone you know
                        login();
                    }
                });
            };
            (function() {
                var e = document.createElement('script');
                e.type = 'text/javascript';
                e.src = document.location.protocol +
                    '//connect.facebook.net/en_US/all.js';
                e.async = true;
                document.getElementById('fb-root').appendChild(e);
            }());
            function login(){
                FB.api('/me', function(response) {
                    document.getElementById('login').style.display = "block";
                    document.getElementById('login').innerHTML = response.name + " succsessfully logged in!";
                });
            }
            function logout(){
                document.getElementById('login').style.display = "none";
            }
            //stream publish method
            function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
                FB.ui(
                {
                    method: 'stream.publish',
                    message: '',
                    attachment: {
                        name: name,
                        caption: '',
                        description: (description),
                        href: hrefLink
                    },
                    action_links: [
                        { text: hrefTitle, href: hrefLink }
                    ],
                    user_prompt_message: userPrompt
                },
                function(response) {
                });
            }
            function showStream(){
                FB.api('/me', function(response) {
                    //console.log(response.id);
                    streamPublish(response.name, 'Thinkdiff.net contains geeky stuff', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
                });
            }
            function share(){
                var share = {
                    method: 'stream.share',
                    u: 'http://thinkdiff.net/'
                };
                FB.ui(share, function(response) { console.log(response); });
            }
            function graphStreamPublish(){
                var body = 'Reading New Graph api & Javascript Base FBConnect Tutorial';
                FB.api('/me/feed', 'post', { message: body }, function(response) {
                    if (!response || response.error) {
                        alert('Error occured');
                    } else {
                        alert('Post ID: ' + response.id);
                    }
                });
            }
            function fqlQuery(){
                FB.api('/me', function(response) {
                     var query = FB.Data.query('select name, hometown_location, sex, pic_square from user where uid={0}', response.id);
                     query.wait(function(rows) {
                       document.getElementById('name').innerHTML =
                         'Your name: ' + rows[0].name + "<br />" +
                         '<img src="' + rows[0].pic_square + '" alt="" />' + "<br />";
                     });
                });
            }
            function setStatus(){
                status1 = document.getElementById('status').value;
                FB.api(
                  {
                    method: 'status.set',
                    status: status1
                  },
                  function(response) {
                    if (response == 0){
                        alert('Your facebook status not updated. Give Status Update Permission.');
                    }
                    else{
                        alert('Your facebook status updated');
                    }
                  }
                );
            }
        </script>
        <h3>New Graph api & Javascript Base FBConnect Tutorial | Thinkdiff.net</h3>
        <p><fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button></p>
        <p>
            <a href="#" onclick="showStream(); return false;">Publish Wall Post</a> |
            <a href="#" onclick="share(); return false;">Share With Your Friends</a> |
            <a href="#" onclick="graphStreamPublish(); return false;">Publish Stream Using Graph API</a> |
            <a href="#" onclick="fqlQuery(); return false;">FQL Query Example</a>
        </p>
        <textarea id="status" cols="50" rows="5">Write your status here and click 'Status Set Using Legacy Api Call'</textarea>
        <br />
        <a href="#" onclick="setStatus(); return false;">Status Set Using Legacy Api Call</a>
        <br /><br /><br />
        <div id="login" style ="display:none"></div>
        <div id="name"></div>
    </body>
</html>
:)

Related Posts

PHP SDK & Graph API base Facebook Connect Tutor

No comments:

Post a Comment