Today Facebook released their updated JavaScript SDK. Now the authentication system is based on OAuth 2.0 and HTTPS. So I updated my previous tutorial by writing this new post. In this post I’ll show you using javascript how could you easily integrate facebook connect (login/logout) features in your site. Additionally how to use Facebook API to get user’s information. Here I only used JavaScript no back-end PHP or any server side language.
In this tutorial I’ll explain:
- Facebook Authentication Process
- Facebook new JavaScript Usage
- Facebook Connect Authentication
- How to get extended permission to get more informations
- How to use graph api
- How to show stream publish prompt and share prompt
- How to publish post in user’s wall using graph api
- How to get additional information by FQL Query
- How to set status using old legacy api (REST api) calling
- How to show ajax loader when interactive with facebook
1. Facebook Authentication Process
This is how facebook authorization process will work. We will follow this process in code.

2. Facebook new JavaScript Usage
So in the figure you are seeing how authentication will work in your site. Now we will implement that. 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. Remember oauth: true is new addition in this latest javascript sdk that enables your site for OAuth 2.0 authentication.
window.fbAsyncInit = function() {
FB.init({ appId: 'Your_APP_ID',
status: true,
cookie: true,
xfbml: true,
oauth: true});
showLoader(true);
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
if (response.authResponse) {
//user is already logged in and connected
FB.api('/me', function(info) {
login(response, info);
});
button.onclick = function() {
FB.logout(function(response) {
logout(response);
});
};
} else {
//user is not connected to your app or logged out
button.innerHTML = 'Login';
button.onclick = function() {
showLoader(true);
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
}, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
This is the most efficient way to load the javascript SDK in your web 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
<!DOCTYPE html> <html xmlns:fb="https://www.facebook.com/2008/fbml">
3. Facebook Connect Authentication
On the first part of the code you will see 2 Facebook api functions called
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
After loading the facebook javascript library, this method getLoginStatus() called and checked the user authentication status and it will send the response to updateButton() method.
FB.Event.subscribe() this method registered the auth.statusChange with facebook. That means if user successfully login or authorized your app or logout or cancel login process, it will trace that and call updateButton() method with the response. In this updateButton() method you’ll see the code of authentication that follows the first figure. In the full source code you’ll see 2 additional methods
function login(response, info){
if (response.authResponse) {
var accessToken = response.authResponse.accessToken;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name
+ "<br /> Your Access Token: " + accessToken;
button.innerHTML = 'Logout';
showLoader(false);
document.getElementById('other').style.display = "block";
}
}
function logout(response){
userInfo.innerHTML = "";
document.getElementById('debug').innerHTML = "";
document.getElementById('other').style.display = "none";
showLoader(false);
}
Those are called when user successfully login and authorized your app and when user logout.
4. How to get extended permission to get more informations
On the first part of the code you’ll see the code that will run when user click login.
//user is not connected to your app or logged out
button.innerHTML = 'Login';
button.onclick = function() {
showLoader(true);
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
}, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
}
In this part you’ll see scope where you can provide extended permission parameters name. Don’t provide all permissions, only think which information you may need for your site. Here is details about permissions.
{scope:'email,user_birthday,status_update,publish_stream,user_about_me'}
5. How to use graph api
In the new javascript sdk, the authentication code is only changed, everything else remains same. To fully understand graph api visit the link . Now i’ll show you, how to use graph api using javascript sdk. There is a method FB.api . Using this method you can call graph api.
FB.api('/me', function(response) {
alert(response.name);
});
By calling this method it will show logged in user name. For another example check 7 number point.
6. 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.
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
showLoader(true);
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) {
showLoader(false);
});
}
function share(){
showLoader(true);
var share = {
method: 'stream.share',
u: 'http://thinkdiff.net/'
};
FB.ui(share, function(response) {
showLoader(false);
console.log(response);
});
}
You’ve to provide parameters when you call streamPublish() method.
function showStream(){
FB.api('/me', function(response) {
//console.log(response.id);
streamPublish(response.name, 'I like the articles of Thinkdiff.net', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
});
}
7. How to publish post in user’s wall using graph api
In my demo you’ll see another customized method named graphStreamPublish(). This is also a graph api example.
function graphStreamPublish(){
showLoader(true);
FB.api('/me/feed', 'post',
{
message : "I love thinkdiff.net for facebook app development tutorials",
link : 'http://ithinkdiff.net',
picture : 'http://thinkdiff.net/iphone/lucky7_ios.jpg',
name : 'iOS Apps & Games',
description : 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'
},
function(response) {
showLoader(false);
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
This method uses FB.api() and does a HTTP POST request to http://graph.facebook.com/me/feed url with some parameters to publish a feed on user’s wall.
8. How to get additional information by FQL Query
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
function fqlQuery(){
showLoader(true);
FB.api('/me', function(response) {
showLoader(false);
//http://developers.facebook.com/docs/reference/fql/user/
var query = FB.Data.query('select name, profile_url, sex, pic_small from user where uid={0}', response.id);
query.wait(function(rows) {
document.getElementById('debug').innerHTML =
'FQL Information: '+ "<br />" +
'Your name: ' + rows[0].name + "<br />" +
'Your Sex: ' + (rows[0].sex!= undefined ? rows[0].sex : "") + "<br />" +
'Your Profile: ' + "<a href='" + rows[0].profile_url + "'>" + rows[0].profile_url + "</a>" + "<br />" +
'<img src="' + rows[0].pic_small + '" alt="" />' + "<br />";
});
});
}
9. How to set status using old legacy api (REST api) calling
You can still use 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.
function setStatus(){
showLoader(true);
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');
}
showLoader(false);
}
);
}
10. How to show ajax loader when interactive with facebook
In the source code you will see a method showLoader(), and you’ll see several places of the source code this method is called.
function showLoader(status){
if (status)
document.getElementById('loader').style.display = 'block';
else
document.getElementById('loader').style.display = 'none';
}
Full Source Code of this project. Or direct download from github
<!DOCTYPE html>
<html xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>New JavaScript SDK & OAuth 2.0 based FBConnect Tutorial | Thinkdiff.net</title>
<!--
@author: Mahmud Ahsan (http://mahmud.thinkdiff.net)
-->
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
var button;
var userInfo;
window.fbAsyncInit = function() {
FB.init({ appId: 'YOUR_APP_ID',
status: true,
cookie: true,
xfbml: true,
oauth: true});
showLoader(true);
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
if (response.authResponse) {
//user is already logged in and connected
FB.api('/me', function(info) {
login(response, info);
});
button.onclick = function() {
FB.logout(function(response) {
logout(response);
});
};
} else {
//user is not connected to your app or logged out
button.innerHTML = 'Login';
button.onclick = function() {
showLoader(true);
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
}, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
function login(response, info){
if (response.authResponse) {
var accessToken = response.authResponse.accessToken;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name
+ "<br /> Your Access Token: " + accessToken;
button.innerHTML = 'Logout';
showLoader(false);
document.getElementById('other').style.display = "block";
}
}
function logout(response){
userInfo.innerHTML = "";
document.getElementById('debug').innerHTML = "";
document.getElementById('other').style.display = "none";
showLoader(false);
}
//stream publish method
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
showLoader(true);
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) {
showLoader(false);
});
}
function showStream(){
FB.api('/me', function(response) {
//console.log(response.id);
streamPublish(response.name, 'I like the articles of Thinkdiff.net', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
});
}
function share(){
showLoader(true);
var share = {
method: 'stream.share',
u: 'http://thinkdiff.net/'
};
FB.ui(share, function(response) {
showLoader(false);
console.log(response);
});
}
function graphStreamPublish(){
showLoader(true);
FB.api('/me/feed', 'post',
{
message : "I love thinkdiff.net for facebook app development tutorials",
link : 'http://ithinkdiff.net',
picture : 'http://thinkdiff.net/iphone/lucky7_ios.jpg',
name : 'iOS Apps & Games',
description : 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'
},
function(response) {
showLoader(false);
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
function fqlQuery(){
showLoader(true);
FB.api('/me', function(response) {
showLoader(false);
//http://developers.facebook.com/docs/reference/fql/user/
var query = FB.Data.query('select name, profile_url, sex, pic_small from user where uid={0}', response.id);
query.wait(function(rows) {
document.getElementById('debug').innerHTML =
'FQL Information: '+ "<br />" +
'Your name: ' + rows[0].name + "<br />" +
'Your Sex: ' + (rows[0].sex!= undefined ? rows[0].sex : "") + "<br />" +
'Your Profile: ' + "<a href='" + rows[0].profile_url + "'>" + rows[0].profile_url + "</a>" + "<br />" +
'<img src="' + rows[0].pic_small + '" alt="" />' + "<br />";
});
});
}
function setStatus(){
showLoader(true);
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');
}
showLoader(false);
}
);
}
function showLoader(status){
if (status)
document.getElementById('loader').style.display = 'block';
else
document.getElementById('loader').style.display = 'none';
}
</script>
<h3>New JavaScript SDK & OAuth 2.0 based FBConnect Tutorial | Thinkdiff.net</h3>
<button id="fb-auth">Login</button>
<div id="loader" style="display:none">
<img src="ajax-loader.gif" alt="loading" />
</div>
<br />
<div id="user-info"></div>
<br />
<div id="debug"></div>
<div id="other" style="display:none">
<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>
<br />
<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>
</div>
</body>
</html>
Additionally if you use PHP SDK 3.0 or this new way of javascript sdk to authenticate your site you can enable oAuth Migration in the application setting.
Hope it will help you to understand new javascript sdk.










Another nice post. Thank You Mahmud vai
hi,
for desktop app using javascript sdk we need to enter redirect_uri in options of application ?
Venkatesh
You can manually write the redirection code within this code block, but when redirect, provide extra parameter and trace that, otherwise user will fall in redirection loop.
if (response.authResponse) { //user is already logged in and connected FB.api('/me', function(info) { login(response, info); }); }I don’t undertand how I should put it together:
redirect_uri
and
if (response.authResponse) {
//user is already logged in and connected
FB.api(‘/me’, function(info) {
login(response, info);
});
}
If I would like to give my user access to my site (page) where my user is loggedin. How do I do it?
Source code got nothing …just readme.txt and image file….would you please give me link that can download the source code?
i like ur posts…thanks
Any hint how to use php-sdk 3.0 together with the new js-sdk for login?
Code does not for me. I see only Login button and nothing else. Button does not work.
This is a good tutorial but assuming you are doing a mysql store on the users, how can you login by cross-referencing your own database for users already registered to retrieve data you’ve collected?
How do you use an RFID tag to post a places message direct from a server instead of browser>server>login?
Couple of sites I have seen use this (rfid reader) without a browser but cannot figure out the process
Any help?
Sorry I don’t know what is RFID tag.
hi,
Permission is required after going to application page but i want to know how i will go to permission pop up directly when accept the application request…but all in javascript.
I am implementing the simple FB credits sample BFF app (PHP) for my game but when users clicks the pay now button, the payment box does not appear.
On the back end it looks like the signed request was not passed through. Is it a problem with the call back page? Should I change REQUEST to POST instead?
MY CALL BACK PHP SCRIPT
// parse signed data $request = parse_signed_request($_REQUEST['signed_request'], $secret); if ($request == null) { echo "nothing"; } $payload = $request['credits']; // retrieve all params passed in $func = $_REQUEST['method']; $order_id = $payload['order_id']; if ($func == 'payments_status_update') { $status = $payload['status']; // write your logic here, determine the state you wanna move to if ($status == 'placed') { $next_state = 'settled'; $data['content']['status'] = $next_state; } // compose returning data array_change_key_case $data['content']['order_id'] = $order_id; } else if ($func == 'payments_get_items') { // remove escape characters $order_info = stripcslashes($payload['order_info']); $item_info = json_decode($order_info, true); //Per the credits api documentation, //you should pass in an item reference // and then query your internal DB for the proper //information. Then set the item //information here to be returned to facebook //then shown to the user for confirmation. if ($item_info == "1a") { $item['title'] = 'BFF Locket'; $item['price'] = 1; $item['description']='This is a BFF Locket...'; $item['image_url']='http://www.facebook.com/images/gifts/21.png'; $item['product_url']='http://www.facebook.com/images/gifts/21.png'; } //for url fields, if not prefixed by http:, //prefix them $url_key = array('product_url', 'image_url'); foreach ($url_key as $key) { if (substr($item[$key], 0, 7) != 'http://') { $item[$key] = 'http://'.$item[$key]; } } $data['content'] = array($item); } // required by api_fetch_response() $data['method'] = $func; echo json_encode($data); ?>I am forever indebted to you for this infomairton.
Hi Mahmud,
Thanks for providing all these great facebook tutorials.
One question i want to ask you is that, I used one of your graph api App and the problem is that when i look at the “Application Settings” page it shows the access token expire date just after 1 hour.
So that means i am not able to further test my application, the redirect url simply doesn’t work as the access token is invalid.
Can you suggest me any workaround for this.
Thanks
Hey, does this new javascript sdk works with the php sdk v.3.0.1? How can i use the php with this?
Hi, I like the way you have described. Please share the source code link. My question is, can we use the same code to post a wall offline when user is not connected in facebook. Please give your pointer on this. It will be really helpful.
how can i get and save user’s facebook id and access token in db, i m using php but wanna connect using javascript sdk
Hello, I see there are already 3 questions about mutual
work of new JavaScript SDK with new PHP SDK. I spent
several hours today trying to make login with XFBML login button and FB.Login methood, but PHP SDK don’t see that
user is logged.
Please let as know if you have confirmation that it is possible. I suggest to make a new blog post about it
with all tips and tricks. Thank you for all your great work.
Hi,
very nice tutorial, but it is very strange it is not working even if i use the complete code. I copied the source code from:http://thinkdiff.net/demo/newfbconnect1/jssdkouth2.html and replace the app id with my one.
so far so good. if i open my new site, i push the login button, but nothing happens. i already added some console output in the js, but not any output. if i am connected the facebook already, the new site recognize this, and show me the logout button. if i press it, logout works, and NOW the login also. if i refresh the page since i am not connected with facebook the login button do not work. have you any hint what the problem is here? Thanks in advance
Peter
I love your stuff, but I’m playing with the idea of using the javascript sdk and php. The problem I’m running into is that I’m not sure how to use the javascript and then create a user row in our database and authenticate with our site. Any help would be appreciated.
I love your tutorials and examples, the best ressource for FB-Development. ThX!
And as the others mentioned, an Example for JS & PHP-SDK together would be great. The new bug-fixed PHP-SDK is out now (3.1.1), and it should work together with JS-SDK and oAuth.
Thanks for your information, if I could manage some time definitely I’ll write a new post.
Login button not working….. but live demo is worked,pls help me
Hi! As other people requested can you write a PHP SDK too? and the share pop up doesn’t work in ie8, any ideas?
Btw, Thanks for the cool info!
Hi Mahmud,
Thanks for providing all these great facebook tutorials.
One question i want to ask you is that, I used one of your graph api App and the problem is that when i look at the “Application Settings” page it shows the access token expire date just after 1 hour.
This is a good tutorial but assuming you are doing a mysql store on the users
How can i get and save user’s facebook id and access token in db
I love your tutorials and examples, the best ressource for FB-Development.
Hey, I just wanted to say thanks a million for this post. I had a little question though. When used in a page with Disqus comments, it seems that Disqus overwrites my appid. Is there a way to prevent this? Thanks again!
For the people who are having trouble getting more than a login button to show up.
I had the same exact problem. After some debugging in firebug, I found the following:
* the code looks for (well, not really requires) an animated gif (ajax-loader.gif). I don’t think it’s necessary for the code to work, but it gives you status of loading.
* more importantly, you should make sure the app id you are using is valid AND your are serving your page from something that matches the URLS you have registered for the app id. Facebook does not seem to be returning the javascript sdk if that is not the case. You can figure out if this is the case for you by running something like firebug and checking to see if you are getting the fb scripts.
Do i have to install any environments for these app?
I intend to add apps/ functions help my site viewers can comment on post using Twitter, Google, Facebook, Zing account (without Disquis).
thx mahmud.
Thank you Mahmud for the script!
If anyone is using this with an AJAX site, you might notice that the script only runs once. If you want it to run again, add the following two lines at the start:
if (window.FB) delete window.FB;
if (window.fbAsyncInit) delete window.fbAsyncInit;
Hi,
Nice post
How can i put a data in a database (this name for exemple) (i want to know if the user is register on my site)
thx
How To Publish Feed and Status Update Direct to Pages and Groups ,Any
Idea.Kindly provide me solution
Hi there. First off, thanks for your tutorials.
I’ve tried both your invite method and the FB.ui({ method: ‘apprequests’,
message: ‘Here is a new Requests dialog…’}); method and though I’m getting a list of friends, the requests don’t seem to be reaching them Is there a way for me to debug this?
Thanks.
Egads…guess it would help if I realized that having the app in Sandbox mode means you can’t send request to non-developers.
Excellent Article … helped me to solve big issue …
thanks mahmud ahsan
Hello Evveryone…I am totally new to FB app development.
My First app is a simple 3 html page program
1) A simple html landing page with a button asking the user to go to app. This click opens OAuth popup and registers user…I have used a simple dialog oauth redirect. I am also getting the reponse type as access token.
2) A simple form with options to select and submit to see the result
3) Result.htm page showing an image.
My prob is how to use the access token on page 2 or shud I reload the JS sdk for fb on this page as well, tho I am nt doing anything with it there but I surely need the token on page 3 as I want to tag and upload the image on user’s profile.
Can anybody help me with it. I would appreciate some steps I need to follow and a piece of code.
P.S I am trying to to this using javascript..no php no jsp jst simple html and javascript.
Awesome post Mahmud!
My question is whether it is possible to access the user’s friends list (I have read that it is) and then be able to tag friends in the textarea.
I am working on a project and the ability to do this would be extremely helpful.
If it is at all possible then could you possibly post the code???
Many thanks.
Is it just me or is this not working anymore?
Very Good! Keep the info coming…
Thanks Mahmud, for making the steps so much easier!
Thanks for this great great tut Mahmud.
I got it to work with the code inside tags embeded in the html, i moved the code to a .js file and sourced it from my html and it stopped working. Is this something to do with the FB async calls?
http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/
Is this Api no longer working after the 1 october ?! Thanks for your answers
Mahmud,
Thank you for taking the time and posting this. I had a question though: in the facebook authentication process (your part #2 above) is there a way to check and see if the user is connected to my app after checking to see if they are already logged into facebook and then change the button to either login or register based on that?
The reason for me asking that is that I am also saving the userid and email to my own database after the user connects to my site for the 1st time just in case facebook authentication stops working or they change anything and for any reason my users cannot connect. In that case they would be able to retrieve a temporary password using their email address and still log in to my site using my own log in. I just do not want to check my database every single time a user logs in to see if they have already been added and think it would be better to check the “connected” status and act based on that.
I already tried the FB.getLoginStatus(function(response) {
if (response.status === ‘connected’) etc… method but it does not seem to be doing anything?
Mahmud,
Any thoughts on this one?
Please help. I’d like to use instead the usual button. How can I tweak the code? Thank you so very much.
Ups sorry. seems the tag has been auto stripped. I mean I’d like to use fb:login-button fbml button. Thanks.
My idea is to use the button also but it seems to not be working with the registration-url attribute if oauth is set to true which I believe is necessary after Oct. 1st?
hey buddy i tried ur application using Demo Application…. it is awesome but when i copied ur code & tried to execute it….it is not working ….even i replaced ur app id with mine app id…..but not working …it is just giving a button with a msg but when i am clicking it …. it is not redirecting the page to facebook login page ………….
Steps i followed…….
opened ur code copied in notepad file and saved in a .html file & tried to run
hey i am new to java ……pls help me ….. better if u mail me ur mail address and phone no…… it’s urgent……….. pls help me
Would you please open firebug in firefox to check any javascript error occurred or not. The code is actually quite simple.
hey dude i waiting for ur reply …. its urgent ….please………
You can’t just expect him to respond because you have an urgent issue…
Thanks Daniel, actually its really tough to answer quickly or check comment every time, as I also do a job.
The example code doesn’t work.
Excellent – clearly written – first article I’ve seen on this that really makes sense!
Hi, how can I select the id and message tags from posts that a user liked?
Thank you for your great articles.
One question: For using the stream publish button do I need to get authorization from the user or it’s not needed?
Thank you in advance
You need user’s authorization.
Very Nice tutorial, implemented it, tweaked it and YES : it works!!!!
Question: maybe you can give another post on now what??!!
Meaning: how can we use this info:
1) build a database
2) let the customer know what we know and how they can udate the info ( like for example
groupon )
etc. etc.!
oeps…..didn’t look for more on your site!
plenty of totorials!
Question:
I notice when i try your demo i get 1 request for permission, when i look at my site i get 2 questions for permission??????
test page: http://www.fotogaaf.nl/test.html
How can i fix that??
Screenshots:
your request for permission : http://www.fotogaaf.nl/facebook/1.png
my 2 requests for permission: http://www.fotogaaf.nl/facebook/2.png & http://www.fotogaaf.nl/facebook/3.png
Looking forward to your answer!
Can Anybody help me with this issue????
hi roy ,
I am facing same problem …please reply me if you got solution
Hi Mahmud
Truly a good post – I have been struggling with the PHP sdk et al and this new post using javascript SDK and OAuth 2 seems very good. I suspect we can use PHP SDK in conjunction with Javascript SDK – it wouldn’t make sense if they could not co-exist.
With respect to your comment in an earlier post about lack of time etc. do you envisage providing a paid for QnA service – I think many of us would be happy to ‘donate’ or pay for answers to our FB / Javascrip / PHP issues.
Thanks anyway
Jerry
@mahmud ahsan
This is very urgent.Please i am using this code .my problem is that i have downloaded ur code but the login button is not working . i mean there is no action is generating after clicking the login button ..can u please tell me how to solve it dude.i am using this in my website.but it should be working when i use it simply after downloading it .i have changed the api id still i am not getting what to do .i have a deadline .can u please tell me why your code is not working after downloading it ,…..
please reply as soon as possible…..
dude is it important to upload this code to the server where my website is !!!!! i mean to say that if i use this code on the localhost then it will be working or not??? i mean i just copied ur code in the notepad and change it to html file..its not working.i have alos tried with the eclipse the thing is not working ..
i am thinking like i have to upload ths code on to server to match with the url which i have registered with facebook … m i explaining correct… please do reply reply fast !!!!!
Hi,
This post was useful. i tried. no what am trying to do is i want to post on the facebook wall even if am not online on facebook(im logged out of fb). i extended teh permission giving offline access. but now when i refresh the page it gain goes back to login button. how to stop it and post on wall without needing to login again.
i m very new to FB coding. pls help.
Hello,
I am trying for 2 days now to set my application to ask user for permissions. It just won’t work,
Using your application works, but when I am using my appid after the login interface, it brings me back to my website.. so I suppose it is something wrong with my application. Is there any way you can tell me what settings to have on facebook api page since that was updated meantime and won’t match your screenshot.
Greatly appreciated!
Cool. But how can we store u_id and how can we use them? I checked codes but everything is JavaScript. Do we need to use ajax to parse all of them to php for this purpose, or need another method?
I also read yours PHP SDK 3.0 & Graph API base Facebook Connect Tutorial, but it didn’t work.
Thank you,
I notice when i try your demo i get 1 request for permission, when i look at my site i get 2 questions for permission??????
test page: http://mm.matrixcsi.com
How can i fix that??
Screenshots:
your request for permission : http://www.fotogaaf.nl/facebook/1.png
my 2 requests for permission like: http://www.fotogaaf.nl/facebook/2.png & http://www.fotogaaf.nl/facebook/3.png
please reply
the code which u have given in (http://thinkdiff.net/facebook/new-javascript-sdk-oauth-2-0-based-fbconnect-tutorial/) is working fine in demo. But itz not working when we use the same code in my site i.e., login button is not working fine when we try.
Hi Mahmud
Nice post and very much help full,but the above code is working only in html page ,could you please clarify that how to make it work in an aspx page. In aspx page the dialog box is not
disappearing after giving the login credentials, please help me…
thanks
how r u doing this in apsx page. Can you please share the code.
how r u doing this in aspx page. Can you please share the code.
The above code is working fine when we are utilising it for demo in the same page. But when we are using the same code in our server LOGIN button is working only 2-3 times then itz not working fine. Can any body help me in resolving this problem.
how to sign in to facebook chat OAuth2.0 based with gloox?
I used gloox to chat with my facebook buddy, and the authentication mechanisms is X-FACEBOOK-PLATFORM.
Now I use OAuth1.0 facebook sdk, but facebook will change the sdk to OAuth2.0. and I do not know how to sign in to facebook chat with the access token.
now my Chat Authentication code before connection as follows:
client_.setSASLMechanisms( SaslMechFacebook );
string key(ini.api_key);
key += “|” + string(password) + “|” + string(ini.secret_key); //password is the session key facebook returned
client_.setAuthcid( key );
How to change this code to adapt to the OAuth2.0?
did you find out?
I’m needing to do that right now.
Thanks bro good job……….
You Sir are a gentleman and a scholar! This tutorial was of utmost delight! I actually got my FB code up and running thanks to you!
the html ppage shows only login button. when i click on it it do anything… how to work out pls explain briefly…… Thanks.
HI..
this article is awesome..it worked fyn for me …
But there is a problem like i want to access the user’s info across all the pages in my web site..how can i achieve this in asp.net??
Waiting for your Reply…
HI Vik,
for me it shows only login button and it does nothing.
pls help me…….
HI Vik,
pls help me…….
Thanks for this helpful post. Could you please tell me how to get facebook userid using your code?
If I download your source code and add my application id in jssdkouth2.html and upload it at my site, should this work?
For me, its not working. Is there any settings required at fb?
Superb post! Its working in all browser except Firefox and IE ? It showing some errors in when looking in web developer is showing error like :
uncaught exception: Error: Permission denied for to get property Proxy.InstallTrigger
Can you help me to understand why it is coming? please
Hi Mahmud Ahsan
I am new to FB praogramming
wish u a very happy new year and really very thankful for your great posts all are very nice as well as helpful.
but i have doubt wen i am logged out from my site then automatically again logged in into my website could u help me here hw can i handle this autologin
great tutorial
but i have some problem with XD proxy when the login box opens
it opens the box and hangs doesn’t complete the process
any solution for this case?
Hi mahmud,
Thanks For this post this help me a lot. And this is exactly what i was looking for, i did lots of googling but this is the best article that i found yet on FB integration. Again Thanx a lot…:))
Amandeep
Hi,
Found your post helpful…I want to integrate Facebook feeds in SharePoint 2010 application.I am referring Facebook Graph javascript SDK. My requirement is that the user is not prompted again and again to login with Facebook credentials. I am able to get the access token through code.
Any help would be highly appreciable
—————————-
Vipul Jain
Hi Mahmud and a Happy new year!
Really cool script… only issue Im having (and appears in your demo too) is the Share with Friends link doesn’t seem to work… any solution?
Thanks
george
Thanks for the great Oauth example! For any one that is unable to get the Login working from localhost or 127.0.0.1, make sure you add it as a site url in the developer facebook apps settings under “website”
hiii to all
can any one find the problem in this method ,with this method actually one can post a link on friends wall but it is not working,please help me.
function share(){
showLoader(true);
var share = {
method: ‘stream.share’,
u: ‘http://www.mobizill.com’
};
FB.ui(share, function(response) {
showLoader(false);
console.log(response);
});
}
This is the best tutorial I have found on the internet. Well explained and keep it coming!
I tried it today ..its not working…
Hi Sona,
Try this code.It working in my project.
require “facebook.php”;
define(‘FBApiAppId’,FBApiAppId);
define(‘FBApiSecret’,FBApiSecret);
$facebook = new Facebook(array(
‘appId’ => FBApiAppId,
‘secret’ => FBApiSecret,
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who’s authenticated.
//$user_profile = $facebook->api(‘/me’);
$uid = $facebook->getUser();
$friends = $facebook->api(array(
“method” => “fql.query”,
“query” => “SELECT uid,name,pic_small FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())”
));
//echo “”; print_r($friends);exit;
}
catch (FacebookApiException $e) {
//echo ”.htmlspecialchars(print_r($e, true)).”;exit;
$user = null;
}
}
Hey guys!
If you try this tutorial in your server, and when you click the login button but it doesn’t do anything it’s probably because your facebook app in sandbox mode!
Aaaah!!! Thank you Reden87!
I’ve spent 12 hours trying to find out why this doesn’t work.
Turning off sandbox mode was the simple solution.
I am Facing two issues :
1) When user login, the login pop up appears and Extended permissions steps once user clicks allow it kept open and showing blank pop up
2) When user clicks on Share With Your Friends, only the loader image kept on showing
3) Kindly advice how can I extract users friends list
Reference URL
http://apps.facebook.com/simply-we
Is anyone having problem with safari, ie7 and ie8?
PS. In my case I am implementing it inside a canvas (Facebook app).
Hello,
Thanks for nice script. I have one issue. This script is working fine with all browser for Windows Xp but it is not working in MAC OS safari browser, firefox and crome browser. I have to reload page 2 times to run the same page in MAC OS…
Please give me suggession..
Waiting for your positive reply..
Hi,
first at all thanks for your work, really useful, but as some people said before, I can make the source code run, and my application is not in sandbox mode as someone suggested, any clue about what is happening?
Hi mahmud,
This article is very useful for all programmers according to me,
But i cant create event out of facebook with javascript sdk.
How can i create event out of facebook using with Facebook Javascript Sdk?
Nearly all examples i found not worked.
Hi Zaki, I never checked or used event api. So please facebook wiki or their official forum for help.
Thanks for posting this!!!
hi, does anyone know how to save user data in a db? Why do I need to pass javascript variables to php, and as I do? Does anyone know of any example? Thanks.
Thanks for nice script. I have one issue. This script is working fine with all browser for Windows Xp but it is not working in MAC OS safari browser, firefox and crome browser. I have to reload page 2 times to run the same page in MAC OS…
Share With Your Friends is not working, kindly help
i have the same problem can anyone help
all the codes i have search is in PHP . and i am
with jsp javascript .
How do you handle expired Facebook tokens? Facebook tokens expire in ~2 hours. So if the user is logged into the app and then tries to post to Facebook after the token is expired, how do you handle that exception?
Can we provide hyper link to Caption in stream publish method?
Thank You
Mahmud Ahsan, hi.
Does facebook change something in the javascript sdk api?
Try yourself, click in your demo Login, after logged in – click Logout.
after this try to push this button and login again.
1st: button doesn’t change text to Login
2nd: firebug says ‘FB.logout() called without an access token.’
3rd: it doesn’t logged in to facebook again =(
solved! the problem was with FB.event.subscribe. I’m just changed auth.statusChange to another listener – auth.authResponseChange
this source code was downloaded, but not working in my site.
i can’t identify the problem. tell me what is the reason?
Working fine with html page but, when i implement it on aspx page fb return blank and popup not close.
Any Idea?
Does this code works the same but for mobile version?
dude, are you kidding us? )
what do you mean on ‘mobile version’?
facebook has a lot of SDK’s, in this example we use javascript SDK, also they have iOS SDK and Android SDK, look here https://developers.facebook.com/docs/sdks/
it’s amazing ……..but I want to know how i can hide the button login after I clicked on it
(function(){
$(‘#your_button_id’).on(‘click’,function(){
$(this).hide();
})
})()
thanks,
sorry I’m beginner where should I put this code.
so.. that means you don’t know about jQuery
okay, try this. put this into your html document (preferably at the bottom of page, over )
var button=document.getElementById(‘fb-auth’);
button.onclick=hide_button
function hide_button(){
button.style.display = ‘none’;
}
over CLOSING body tag. blog cut tags
it’s not work
I use the code below this sentence: Full Source Code of this project. Or direct download from github,and I want to integrate hide button with it.
hey buddy, anyway biggest part from this tutorial doesn’t work too, as you can see comments of another people) you have to fix a lot from topic-starter’s code and then think about your button )
my advice: try to find a better solution on the web, and.. looks like you began too early to play with facebook api. learn at least javascript first
sorry but that code run with me and post to my wall without any problem
you make me nervous)
what button you need to hide ?
I’m really sorry,
in code we have this button:Login
and I need to hide it after click on it
JavaScript code what i gave to you.. did you wrapped it in script tags?)
i said, blog cutted the tags
try this:
http://jsfiddle.net/eVcEz/
I’m really sorry,
in code we have this button:
Login
Hi, I just want to ask a single question: I’m going to develop a website for a contest with the Facebook Connect integration, to collect data from users and publish some posts on the users timeline.
Do I need to buy an SSL certificate to let websites use the FB connect function and use the Graph API and so on, obviously requiring all the necessary permissions when implementing the login?
The SSL certificate is necessary only when building app inside Facebook (app.facebook.com/whateveryouwant) or not?
i want to ask how i can do it like yahoo when somebody clicked on the post and doesn’t have permission, the app show to him authorize dialog and after he accept the permission he can see the article
I want to ask question :
How can I make this code post to my way one-time only to the similar url.
and thanks for all.
sorry to my wall not to my way
HI or Ciao
I’m testing an app using or
Client-side Authentication,
or your OAuth 2.0 based FBConnect tutorial
scope: email,status_update,publish_stream,user_about_me,user_checkins
everything works I can publish_stream if the user accept the app scopes
in two ways one at the first login and one each time he use the app
(just a test)
The problem is that I’m getting crazy because, when user accept the email permission,
I’m not able to catch where emails are stored
I hope you’ll can give me an help
thanks
Lorenzo
hi,
thanks for the post.
how can I store the data I get through my app on facebook? (for example, birthday, uid etc.)
HI, i have downloaded the same page and its not working for me. is there anythig to be modified to execute jssdkouth2.html.
please help me out to test this sample
Hello,
Very informative tutorial and appreciate such a detailed step by step explanation.
However, how do you ensure the pop-up login window is centered on the screen in Firefox. Right now this window is to the right of the screen
Thank you in advance
Srini
Hi mahmud ahsan, its very simple and easy to understand. Appreciate your great effort!. It would be better if i get an article same like this for Google connect.
using Javascript
Hi,
Thanks for the stuff !
Hello! I am looking for a solution to do my facebook app, can identify differents facebook pages where it could be contained.
I am using just javascript.
Signed_Request seems be the option, but I don´t know how can parse it with js.
Do you know any method or property wich allows a facebook app, know the id of the page wich contains the canvas?
Thank you so much for your help!
Best regards! Matt.-
hi can anyone help me …
How to add a search box of facebook in my website that search for all the comments or post of particular topic or about a person ….
Example: If i type a word like “apj abdul kalam” it has to retrieve all the comments about abdulk kalam and display on my webpage ..
please help me its very urgent for me…….thanks in advance….
by using javascript and html5 i am trying to develop this appliction. please help me
Hi Mahmud, nice post, could you please guide me FBCONNECT in PHP.. I need it..
hey i am trying to execute this piece of code. at first it execute successfully but now its stuck. i searched lot about the error but can’t find any suitable solution . you are my last hope, actually i am trying to make authentication from facebook to embed in a website, you used login button to if user not login. i want to make a lil difference i want the code to directly move the user if he/she is not logging and show him/her the login page without clicking .
response is “Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the Application configuration. It must match one of the Connect or Canvas URLs or domain must be the same as or a subdomain of one of the Application's base domains.”
please ..
Great Job….. Helpful….
Hi, just wanted to say thank you so much for this code! I spent a few hours trying to get this working- then I found this website with your tutorial.
You are a life saver!
Thanks this script works brilliantly! Only issue I have is “showStream()” function does not show up on mobile devices i.e iPad or iPhone. The loader just goes on indefinitely.
Have your found a solution for this?
Thanks in advance!
P.S. You are in Malaysia now? I lived in KL for 6 months. I love SE Asia
I no longer work on facebook app development. So Please check facebook documentation. Yeah I live in Melaka.
hi tks for this tutorial….But actually i need to have the ad form of facebook on my website that i’m developping with zend, so is there a way to have that form?
Sorry Mahmud, but the source code I downloaded from the above link doesn’t work on my browser (both chrom and Firefox).
I found my problem. I forgot the App API part!
Can I have the list of my subscribers using this api ? Do twitter provide api similar to this? Do you have any tutorial how to write an facebook app ? Kindly do tell me. Regard
Great tutorial. But i don’t unterstand why there is nothing fired when i press the login button.
Thanks for the great tutorial. As mentioned in one of the replies above, if you are running the code on localhost, then in the app settings page, under the section “Select how your app integrates with Facebook”, click on “Website with Facebook Login” and set the site url to http://localhost:port_number and it will work.
Hi from where do i get/download javascript sdk?
’m sure you’ll create lots of successful projects on paper and hopefully you’ll have some fun as well
Great tips, thanks for sharing.
hello,
how can I get user email to the member?
Hi, some times //connect.facebook.net/en_US/all.js doesnot load , im using img for fb connect and fb logout somethimes img does not show ,again if i refresh img appear,
FB.logout(function(response) {
console.log(response.status);
logout(response);
});
is not working for IE , but working in Firefox and Chrome Plz help
Thanks
hi thanks
at the top you draw a good workflow
the code don’t flow it
1. the line no from the user authorized you site are not implement
2. the FB.Event are not draw
Thanks. Very helpful.
Does anyone know how to get user_address and user_mobile_phone?
I can only find this but not an update and whenever I query FB with these field requests it “hangs”
https://developers.facebook.com/blog/post/2011/01/14/platform-updates–new-user-object-fields–edge-remove-event-and-more/
I just downloaded the script and run it on my machine,but it is not running,Do you know what could be the reason?
This is working well. cooooooooooooool.. thanks a looooooooooooooooooooooooooooooot
Hi,
Thanks. But I have a problem. We need to log all the logins! So I send an Ajax request in your login function in order to log it. But I don’t know why the login function is called 2 times! and it ends up in a duplication in our logs!
thanks for the g8 post …but i do have a problem …I have avg installed in my system and it blocks all analytics including //connect.facebook.net/en_US/all.js so clicking on the login button doesn’t work…plz post a workaround it
Hello, I am trying to run the demo of your application on safari but facebook authentication pop up is not coming up. When i run the demo on google chrome or firefox i see the facebook authentication pop up. Please help.
Mahmud Ahsan,
Thank You for you brilliant tutorial. Thanks also for putting time aside into educating others out there. Its very kind of you. Keep it up!
Thank you bro.
hey guys check this out
http://learnwebscripts.com/how-to-login-into-facebook-account-using-php
its very easy to integrate
Has anyone tried using this code within an ASP page? If I simply add a form opening and closing tag to the page, the functionality breaks. Am I missing something simple?
Correction, ASPX page.
Though it seams like the questions are not replied sometimes..
But still I have a question I am putting forward..
This method, even the demo doesn’t work on a symbian phone, can you please make it happen, or if possible .. put forward a new tutorial..
If the login button doesnt work, the other possible situation could be that probably you dont have access to the facebook javascript all.js. Try to download it and work with it locally. And thanks man for the post. Its a great help!!
This has been the best script I’ve seen out there for working with the FB SDK! Great job!!!
Hi all, for those having problems with the login button that isn’t working try this:
In the line of code:
remove the “:none”
that should fix the problem…unless that worked for me
Nice tutorial! thanks to the author
bye
sorry…where it says “in the line of code:” goes: ”
This thing is cutting my comments arrggg
i mean div id=”loader” style=”display:none”
Good show sir. Thank you for making this post and posting the source code.
Hi, i have tried your code in implementing it for phonegap, but i was not able to do anything.
could you help me on this issue.
Hi,
Can you provide us if you have used any .js files or any .js urls for implementing this,
I have tried your same code to integrate the facebook, i have changed the app_id of mine but it seems like nothing is working it is not entering into this
window.fbAsyncInit
method. Could you me in this issue.
thanks in advance
Regards for writing “New JavaScript SDK & OAuth 2.0 based FBConnect Tutorial | Thinkdiff.
net”. I actuallymay undoubtedly end up being returning for more browsing and commenting
soon. Many thanks, Jayme
Hello,
Login button is not working. Please let me know the solution. If i remove display none of loader image. Image is getting displayed but when clicked on Login Button nothing is working. Please someone help.
sorry to translate for my englich, I’m from Germany and use google
I would like to use your script but how do I get name, email id and individually interrogated for a form so that daa form is automatically populated?
such a form cell:
eingestellt von:
such a form cell:
eingestellt von:
Along with these two ingredients, comes swallowing your ego and be willing to do work for
free at first. A working spouse, a loan, a second job and a second supplier
are all critical items. I enjoyed creative things, and came across
the idea of starting a gift basket business.
nice post ….thanks
Hi,
Do u know what code to add in to display a person’s news feed. Like what the get on their home when they log on to facebook desktop site?
clicked on Login Button nothing is working. Please someone help.
bfjhjksadffsdfsdfdsfsfsdfdsdsds