facebook integration fb


step 1 : register your application and your Site URL should be same like local host or site url.

<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml&#8221; xmlns:fb=”http://www.facebook.com/2008/fbml”&gt;
<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: ‘221123731234535’, 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&#8217;, “Share thinkdiff.net”);
});
}

function share(){
var share = {
method: ‘stream.share’,
u: ‘http://thinkdiff.net/&#8217;
};

FB.ui(share, function(response) { console.log(response); });
}

function graphStreamPublish(){
var body = ‘xxxxxxxxxxxxxxxxxxxxxxxxxxx’;
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,user_about_me”></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>

Simple Jquery Ajax


<html>
<head>
<script type=”text/javascript” src=”jquery.js”></script>
<script type=”text/javascript”>
$(document).ready(function(){
$(“button”).click(function(){
$.ajax({url:”test1.php”, success:function(result){
$(“div”).html(result);
}});
});});
</script>
</head>
<body>

<div><h2>Let AJAX change this text</h2></div>
<button>Change Content</button>
</body>
</html>

User’s Basic Data from Facebook


facebookSometimes you may need to collect facebook user’s basic data for your website or application. Then you’ve to call graph api or legacy api or fql query to collect some specific data. This is a basic requirements for most of the fbconnect base website or facebook application.

For this reason, here I’m sharing the code, how could I collect those basic data and store them in database.

Before proceeding check the demo.

If you’re automatically logged in the site, then first logout and relogin and approve all the permissions. Now I’m showing the database table schema first

demographic

MySql code of this schema is:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
CREATE TABLE IF NOT EXISTS `demographic` (
`uid` BIGINT UNSIGNED NOT NULL ,
`first_name` VARCHAR(50) NULL ,
`last_name` VARCHAR(50) NULL ,
`email` VARCHAR(200) NULL ,
`link` VARCHAR(255) NULL ,
`affiliations` VARCHAR(255) NULL ,
`birthday` VARCHAR(50) NULL ,
`current_location` VARCHAR(200) NULL ,
`education_history` VARCHAR(500) NULL ,
`work` MEDIUMTEXT NULL ,
`hometown_location` VARCHAR(400) NULL ,
`interests` VARCHAR(200) NULL ,
`locale` VARCHAR(50) NULL ,
`movies` VARCHAR(500) NULL ,
`music` VARCHAR(500) NULL ,
`political` VARCHAR(200) NULL ,
`relationship_status` VARCHAR(100) NULL ,
`sex` VARCHAR(10) NULL ,
`tv` VARCHAR(200) NULL ,
`status` TINYINT NULL ,
`created` DATETIME NULL ,
`updated` DATETIME NULL ,
PRIMARY KEY (`uid`) )
ENGINE = InnoDB

This code collects data from facebook

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
if ($fbme){
//collect some data using legacy api
$param = array(
'method' => 'users.getinfo',
'uids' => $fbme['id'],
'fields' => 'birthday_date, interests, locale, political, relationship_status, affiliations',
'callback' => ''
);
try{
$info = $facebook->api($param);
}
catch(Exception $o){
error_log("Legacy Api Calling Error!");
}
//using graph api
//array data
$workInfo =   getWorkInfoAsString($fbme);
$education =   getEducationAsString($fbme);
$moviesArr = $facebook->api("/me/movies");
$musicArr = $facebook->api("/me/music");
$televisionArr = $facebook->api("/me/television");
//format some api data
$movies =   getArrayDataAsString($moviesArr['data']);
$music =   getArrayDataAsString($musicArr['data']);
$television =   getArrayDataAsString($televisionArr['data']);
//data from legacy api
$networks = '';
if (!empty($info[0]['affiliations'])){
$flag =   true;
foreach ($info[0]['affiliations'] as $item){
if (!$flag) $networks.= ' # ';
$networks .= $item['name'];
$flag =   false;
}
}
$now = date("Y-m-d G:i:s");
$insData = array(
'uid' => $fbme['id'],
'first_name' => $fbme['first_name'],
'last_name' => $fbme['last_name'],
'email' =>  isset($fbme['email']) ? $fbme['email'] : '',
'link' => $fbme['link'],
'affiliations' => $networks,
'birthday' => $info[0]['birthday_date'],
'current_location' =>  isset($fbme['location']['name']) ? $fbme['location']['name'] : '',
'education_history' => $education,
'work' => $workInfo,
'hometown_location' =>  isset($fbme['hometown']['name']) ? $fbme['hometown']['name'] : '',
'interests' => $info[0]['interests'],
'locale' => $info[0]['locale'],
'movies' => $movies,
'music' => $music,
'political' => $info[0]['political'],
'relationship_status' => $info[0]['relationship_status'],
'sex' =>  isset($fbme['gender']) ? $fbme['gender'] : '',
'tv' => $television,
'status' => '0',
'created' => $now,
'updated' => $now,
);
//$this->db->insert('demographic', $insData);
}
function getWorkInfoAsString($fbme, $delim = '#', $partDelim = ' | '){
$info = "";
$flag =   false;
if (empty($fbme['work'])) return '';
foreach($fbme['work'] as $item){
if ($flag)
$info .= $partDelim;
$flag =   true;
$info .=  (isset($item['employer']['name']) ? $item['employer']['name'] : '' ). $delim .
(isset($item['location']['name']) ? $item['location']['name'] : '' ). $delim .
(isset($item['position'])         ? $item['position']['name'] : '' ). $delim .
(isset($item['start_date'])       ? $item['start_date']       : '' ). $delim .
(isset($item['end_date'])         ? $item['end_date']         : '' );
}
return $info;
}
function getEducationAsString($fbme, $delim = '#', $partDelim = ' | '){
$info = "";
$flag =   false;
if (empty($fbme['education'])) return '';
foreach($fbme['education'] as $item){
if ($flag)
$info .= $partDelim;
$flag =   true;
$info .=  (isset($item['school']['name']) ? $item['school']['name'] : '' ). $delim .
(isset($item['year']['name'])   ? $item['year']['name']   : '');
}
return $info;
}
function getArrayDataAsString($data, $delim = '#', $partDelim = ' | '){
$info = "";
$flag =   false;
foreach($data as $item){
if ($flag)
$info .= $partDelim;
$flag =   true;
$info .= $item['name'];
}
return $info;
}

Look $insData contains all the values. So you just need to insert $insData in your database table. In this example I used mainly graph api, and for some small information I call legacy api. Regarding data storing format, if I found any data as array like education_history then I store that data like below format

[education_history] => International Islamic University Chittagong#2008 | Govt. Shah Sultan College, Bogra#2003

first # for part of a single data like (education institute and year), and finally | that separates array item. If your profile has well filled data then by visiting this demo you will see the data example.

So if you store education_history and next time you need to break them as array then you could write code like

01
02
03
04
05
06
07
08
09
10
11
12
13
14
$arrEdu = explode('|', $education_history); // break string to array items
$education = array();
$i = 0;
foreach($arrEdu as $item){
$brk = explode('#', $item);
$education[$i]['institute'] = $brk[0];
$education[$i]['year']      = $brk[1];
++$i;
}
echo '<pre>';
print_r($education);
echo '</pre>';

This will output

Array
(
    [0] => Array
        (
            [institute] => International Islamic University Chittagong
            [year] => 2008
        )

    [1] => Array
        (
            [institute] =>  Govt. Shah Sultan College, Bogra
            [year] => 2003
        )
)

If you read the code you’ll see its very easy to understand.

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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
<?php
include_once "fbmain.php";
//if user is logged in and session is valid.
if ($fbme){
//collect some data using legacy api
$param = array(
'method' => 'users.getinfo',
'uids' => $fbme['id'],
'fields' => 'birthday_date, interests, locale, political, relationship_status, affiliations',
'callback' => ''
);
try{
$info = $facebook->api($param);
}
catch(Exception $o){
error_log("Legacy Api Calling Error!");
}
//using graph api
//array data
$workInfo =   getWorkInfoAsString($fbme);
$education =   getEducationAsString($fbme);
$moviesArr = $facebook->api("/me/movies");
$musicArr = $facebook->api("/me/music");
$televisionArr = $facebook->api("/me/television");
//format some api data
$movies =   getArrayDataAsString($moviesArr['data']);
$music =   getArrayDataAsString($musicArr['data']);
$television =   getArrayDataAsString($televisionArr['data']);
//data from legacy api
$networks = '';
if (!empty($info[0]['affiliations'])){
$flag =   true;
foreach ($info[0]['affiliations'] as $item){
if (!$flag) $networks.= ' # ';
$networks .= $item['name'];
$flag =   false;
}
}
$now = date("Y-m-d G:i:s");
$insData = array(
'uid' => $fbme['id'],
'first_name' => $fbme['first_name'],
'last_name' => $fbme['last_name'],
'email' =>  isset($fbme['email']) ? $fbme['email'] : '',
'link' => $fbme['link'],
'affiliations' => $networks,
'birthday' => $info[0]['birthday_date'],
'current_location' =>  isset($fbme['location']['name']) ? $fbme['location']['name'] : '',
'education_history' => $education,
'work' => $workInfo,
'hometown_location' =>  isset($fbme['hometown']['name']) ? $fbme['hometown']['name'] : '',
'interests' => $info[0]['interests'],
'locale' => $info[0]['locale'],
'movies' => $movies,
'music' => $music,
'political' => $info[0]['political'],
'relationship_status' => $info[0]['relationship_status'],
'sex' =>  isset($fbme['gender']) ? $fbme['gender'] : '',
'tv' => $television,
'status' => '0',
'created' => $now,
'updated' => $now,
);
//$this->db->insert('demographic', $insData);
}
function getWorkInfoAsString($fbme, $delim = '#', $partDelim = ' | '){
$info = "";
$flag =   false;
if (empty($fbme['work'])) return '';
foreach($fbme['work'] as $item){
if ($flag)
$info .= $partDelim;
$flag =   true;
$info .=  (isset($item['employer']['name']) ? $item['employer']['name'] : '' ). $delim .
(isset($item['location']['name']) ? $item['location']['name'] : '' ). $delim .
(isset($item['position'])         ? $item['position']['name'] : '' ). $delim .
(isset($item['start_date'])       ? $item['start_date']       : '' ). $delim .
(isset($item['end_date'])         ? $item['end_date']         : '' );
}
return $info;
}
function getEducationAsString($fbme, $delim = '#', $partDelim = ' | '){
$info = "";
$flag =   false;
if (empty($fbme['education'])) return '';
foreach($fbme['education'] as $item){
if ($flag)
$info .= $partDelim;
$flag =   true;
$info .=  (isset($item['school']['name']) ? $item['school']['name'] : '' ). $delim .
(isset($item['year']['name'])   ? $item['year']['name']   : '');
}
return $info;
}
function getArrayDataAsString($data, $delim = '#', $partDelim = ' | '){
$info = "";
$flag =   false;
foreach($data as $item){
if ($flag)
$info .= $partDelim;
$flag =   true;
$info .= $item['name'];
}
return $info;
}
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Facebook User's Demographic Data Collection | Thinkdiff.net</title>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '<?=$fbconfig['appid' ]?>', 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();
});
};
(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(){
document.location.href = "<?=$config['baseurl']?>";
}
function logout(){
document.location.href = "<?=$config['baseurl']?>";
}
</script>
<h3>Facebook User's Demographic Data Collection | Thinkdiff.net</h3>
<?php if (!$fbme) { ?>
You've to login using FB Login Button to see your demographic data
<?php } ?>
<p>
<fb:login-button autologoutlink="true" perms="email,publish_stream,offline_access,user_birthday,user_location,user_work_history,user_religion_politics,user_relationships"></fb:login-button>
</p>
<!-- all time check if user session is valid or not -->
<?php
if ($fbme){
echo '<pre>';
print_r($insData);
echo '</pre>';
}
?>
</body>
</html>

Hope this code will help you to quickly integrate in your project. This data collection code will work in both canvas application and fbconnect base application. You can modify the code easily to get customize data. But fyi this code doesn’t collect all the information of facebook user rather some basic and essential information

And don’t forget extended permission list. I provided this list of permissions as I needed to collect above data.

1

<fb:login-button autologoutlink="true" perms="email,publish_stream,offline_access,user_birthday,user_location,user_work_history,user_religion_politics,user_relationships"></fb:login-button>

Facebook user be aware


According to Facebook new blog post any facebook application now can prompt to user to get his mobile phone number and personal address.

This is very good if the application really needs it but as a facebook user you shouldn’t allow to provide this sensitive information, until you trust the application much. There are many spamming application those collect data from user and may sell those data to third party.

So when you allow an application, check the permission list and think the application really needs it or not. Otherwise you may get in trouble.

Sensitive Information

For developers who want this information for their application, just use 2 new permissions.

1
{perms:'user_address, user_mobile_phone'}

Please remember, most of the facebook applications really don’t need user’s mobile phone number and address.

My Facebook Application


<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml&#8221; xmlns:fb=”http://www.facebook.com/2008/fbml”&gt;
<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: ‘112121205537903’, 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&#8217;, “Share thinkdiff.net”);
});
}

function share(){
var share = {
method: ‘stream.share’,
u: ‘http://thinkdiff.net/&#8217;
};

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’+response.error);
} 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 />” +
‘Your name: ‘ + rows[0].hometown_location + “<br />” +
‘Your name: ‘ + rows[0].sex + “<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>

Graph api & javascript base Facebook Connect tutorial


  • Facebook connect authentication for websites
  • How to use graph api
  • How to show stream publish prompt and share prompt
  • How to run FQL query using javascript
  • 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',
    };
    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>

    :)

    how to increase height and width in canvas in facebook application


    jQuery(document).ready(function () {

    jQuery(“#invite”).bind(‘click’, invite);
    increaseIframeSize(700,900);

    });

    function increaseIframeSize(w,h){
    var obj = new Object;
    obj.width=w;
    obj.height=h;
    FB.Canvas.setSize(obj);
    }

    function invite(){
    FB.ui({ method: ‘apprequests’,
    message: ‘Now Featured Properties On Facebook Here http://apps.facebook.com/cndemo-demo/&#8217;});
    return false;
    }