If you are looking for an easy Ajax solution to connect to Facebook, this simple method could do the trick. In this tutorial you will see how we can connect users to Facebook and let them register on your site easily with their Facebook name and email. All these happens without even refreshing the page. I have used jQuery and Facebook PHP SDK files available at Github. But for your convenience, I have created a zipped sample file, downloadable at the bottom of the page, which already includes SDK and jQuery files
There are basically three PHP files in this tutorial, the purpose of these files is to connect to Facebook and import user details, in order to complete registration or login the existing users.
Configuration file (config.php) basically does nothing but stores settings information, which are needed by Facebook API and database queries, we just include this file wherever needed. Main Page (index.php) is the front page where visitors see Ajax Facebook Connect button. Processing (process_facebook.php) is the important file, because it retrieves, stores user details in database, logs-in user and responds with the result.
I am sure at this point, I am sure you must have created a Facebook application and wrote down its App ID and App Secret.
Run MySql query below in phpMyAdmin to create a table called “usertable“, table containing 4 fields. id(Int, Auto Increment), fbid (BigInt, Facebook ID), fullname(Varchar, Full Name) and email(Varchar, Email). Note that fbid is BIGINT to make sure all long facebook IDs fit in it.
1 2 3 4 5 6 7 | CREATE TABLE IF NOT EXISTS `usertable` ( `id` int(20) NOT NULL AUTO_INCREMENT, `fbid` bigint(20) NOT NULL, `fullname` varchar(60) NOT NULL, `email` varchar(60) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1; |
Configuration File
Insert needed values in config.php file, replace xxxx with your Facebook App ID, App Secret and MySQL database information. Specify return URL and permissions required.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php ########## app ID and app SECRET (Replace with yours) ############# $appId = 'xxxxxx'; //Facebook App ID $appSecret = 'xxxxxxxxxxxxxx'; // Facebook App Secret $return_url = 'http://yoursite.com/connect_script/'; //path to script folder $fbPermissions = 'publish_stream,email'; //more permissions : https://developers.facebook.com/docs/authentication/permissions/ ########## MySql details (Replace with yours) ############# $db_username = "xxxxxx"; //Database Username $db_password = "xxxxxx"; //Database Password $hostname = "localhost"; //Mysql Hostname $db_name = 'database_name'; //Database Name ################################################################### ?> |
Main Page
Main page (index.php) renders “Facebook Connect” button, and logs-in user using jQuery Ajax with click of the button. It uses session variables set in process_facebook.phpto login users, you just have to replace it with some built-in user authentication system, which will instantly check user and log him/her in.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | <?php session_start(); include_once("config.php"); if(isset($_GET["logout"]) && $_GET["logout"]==1) { //User clicked logout button, distroy all session variables. session_destroy(); header('Location: '.$return_url); } ?> <!DOCTYPE html> <html xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="en-gb" lang="en-gb" > <head> <!-- Call jQuery --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> <title>Ajax Facebook Connect With jQuery</title> <script> function AjaxResponse() { var myData = 'connect=1'; //For demo, we will pass a post variable, Check process_facebook.php jQuery.ajax({ type: "POST", url: "process_facebook.php", dataType:"html", data:myData, success:function(response){ $("#results").html('<fieldset style="padding:20px">'+response+'</fieldset>'); //Result }, error:function (xhr, ajaxOptions, thrownError){ $("#results").html('<fieldset style="padding:20px;color:red;">'+thrownError+'</fieldset>'); //Error } }); } function LodingAnimate() //Show loading Image { $("#LoginButton").hide(); //hide login button once user authorize the application $("#results").html('<img src="ajax-loader.gif" /> Please Wait Connecting...'); //show loading image while we process user } function ResetAnimate() //Reset User button { $("#LoginButton").show(); //Show login button $("#results").html(''); //reset element html } </script> </head> <body> <?php if(!isset($_SESSION['logged_in'])) { ?> <div id="results"> </div> <div id="LoginButton"> <div class="fb-login-button" onlogin="javascript:CallAfterLogin();" size="medium" scope="<?php echo $fbPermissions; ?>">Connect With Facebook</div> </div> <?php } else { echo 'Hi '. $_SESSION['user_name'].'! You are Logged in to facebook, <a href="?logout=1">Log Out</a>.'; } ?> <div id="fb-root"></div> <script type="text/javascript"> window.fbAsyncInit = function() { FB.init({appId: '<?php echo $appId; ?>',cookie: true,xfbml: true,channelUrl: '<?php echo $return_url; ?>channel.php',oauth: true});}; (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 CallAfterLogin(){ FB.login(function(response) { if (response.status === "connected") { LodingAnimate(); //Animate login FB.api('/me', function(data) { if(data.email == null) { //Facbeook user email is empty, you can check something like this. alert("You must allow us to access your email id!"); ResetAnimate(); }else{ AjaxResponse(); } }); } }); } </script> </body> </html> |
Process Requests
The process_facebook.php file connects to Facebook and compares user information in database table, if connected user information is not available, it registers user using their Facebook data, storing information in the database. In case user information is already available in database, script responses with a welcome back message & logging him in the your website.
process_facebook.php sets PHP session variables to log-in users. You might want to replace the function with your own in-built authentication system to create users or log-in them into your website.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | <?php session_start(); /* check our post variable from index.php, just to insure user isn't accessing this page directly. You can replace this with strong function, something like HTTP_REFERER etc. */ if(isset($_POST["connect"]) && $_POST["connect"]==1) { include_once("config.php"); //Include configuration file. //Call Facebook API if (!class_exists('FacebookApiException')) { require_once('inc/facebook.php' ); } $facebook = new Facebook(array( 'appId' => $appId, 'secret' => $appSecret, )); $fbuser = $facebook->getUser(); if ($fbuser) { try { // Proceed knowing you have a logged in user who's authenticated. $me = $facebook->api('/me'); //user $uid = $facebook->getUser(); } catch (FacebookApiException $e) { //echo error_log($e); $fbuser = null; } } // redirect user to facebook login page if empty data or fresh login requires if (!$fbuser){ $loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$return_url, false)); header('Location: '.$loginUrl); } //user details $fullname = $me['first_name'].' '.$me['last_name']; $email = $me['email']; /* connect to mysql */ $connecDB = mysql_connect($hostname, $db_username, $db_password)or die("Unable to connect to MySQL"); mysql_select_db($db_name,$connecDB); //Check user id in our database $result = mysql_query("SELECT COUNT(id) FROM usertable WHERE fbid=$uid"); $UserCount = mysql_fetch_array($result); if($UserCount[0]) { //User exist, Show welcome back message echo 'Ajax Response :<br /><strong>Welcome back '. $me['first_name'] . ' '. $me['last_name'].'!</strong> ( Facebook ID : '.$uid.') [<a href="'.$return_url.'?logout=1">Log Out</a>]'; //print user facebook data echo '<pre>'; print_r($me); echo '</pre>'; //User is now connected, log him in login_user(true,$me['first_name'].' '.$me['last_name']); } else { //User is new, Show connected message and store info in our Database echo 'Ajax Response :<br />Hi '. $me['first_name'] . ' '. $me['last_name'].' ('.$uid.')! <br /> Now that you are logged in to Facebook using jQuery Ajax [<a href="'.$return_url.'?logout=1">Log Out</a>]. <br />the information can be stored in database <br />'; //print user facebook data echo '<pre>'; print_r($me); echo '</pre>'; // Insert user into Database. @mysql_query("INSERT INTO usertable (fbid, fullname, email) VALUES ($uid, '$fullname','$email')"); //User is now connected, log him in login_user(true,$me['first_name'].' '.$me['last_name']); } mysql_close($connecDB); } function login_user($loggedin,$user_name) { /* function stores some session variables to imitate user login. We will use these session variables to keep user logged in, until he/she clicks log-out link. If you are using some authentication library, login user with it instead. */ $_SESSION['logged_in']=$loggedin; $_SESSION['user_name']=$user_name; } ?> |
With jQuery connecting to Facebook is super easy, I am sure this will help you make your own Ajax Facebook Connect, any good feedback would be hugely appreciated, Good luck.

Hello, this great script it works very well, by cons I would change it so I can make it work with my site.
How to replace this: login)) {?> Which is on my site??
hi,
i got this error when i try to login :
Notice: Undefined variable: uid in /Applications/MAMP/htdocs/tarba-web/process_facebook.php on line 15
Did you know what’s wrong with my config ?
this errors seems to appear only in webkit browsers and on localhost environment.
i use now FF for development and i didn’t get back this error.
Hi I have one question, the script work very well but is that normal that when I Logout and Login in my database the script create a new user so in my database if i logout 5 times and login 5 times I will have 5 times my information in the database…
i also have the same prob.. did you fiugure it out
It seems like :
$result=mysql_query(“SELECT count(id) FROM usertable WHERE fbid=”.$uid);
$num_rows=mysql_result($result,0);
if ($num_rows>=1) {
}
else{
}
doesn’t work because in my database I have 4 same fbid… so it’s more than 1 but it go directly to “else” anyway…
Try this :
$result = mysql_query(“SELECT id FROM usertable WHERE fbid=”.$uid.” LIMIT 1″);
$num_rows = mysql_num_rows($result);
if ($num_rows>0) {
// do stuff
}else{
// do other stuff
}
Hi very nice script. Is this normal that in localhost all my website is very slow…
Your a Star.
Thank you more than words can say…..
Howdy! Do you know if they make any plugins to
assist with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m
not seeing very good results. If you know of any please share.
Thanks!
Can I reload the page after logging in ? My page hangs on the please wait while connecting
why mine only came out the connect with facebook button?others didn’t came out.
This is great! I am really grateful that I found your post.
I really appreciate that these scripts are available. I have a question, though:
Why is it that you are logging the user in the php script, if they were already logged in the jQuery part?
I mean this instruction in the php:
I believe the user has already been connected when this was executed in the browser:
Because with PHP or any server-side scripting language, you are able to store user details in database, use session variables and do lot more.
Hola
It really very good.. thanx a lot..
i want after this step … post to user’s wall and post photos for user’s album
how can i do that dear
please reply
we can use this data and we can make some edit in php ( post on wall page ) to make it post in users wall ( data mysql saved from this script )
can we make integration
Check this i may help you..
http://developers.facebook.com/docs/getting-started/graphapi/
Hi
I connect to facebook via your script installed on my site and want to pass the user name details into a form.
How to achieve this.
Thanks
Peter
the download page doesnt work it displays encrypted code instead of saving the file to my hd… can you fix it please
I created a facebook app tutorial based on you and it worked perfectly, with only one problem, only the data of the first user who accessed the app that was fied auger in the mysql db, how can I solve this problem?
Hi!
First of all congratulations for the work and the page.
I am trying to implement he piece of code into my site. Everything seems to work properly, when I try to login the process seems to be fine, but the program is not saving nothing into the database, and once the login is done, I am returned to the main page and just the login button is there, no message.
Why can this happen?
Regards!
Download the php sdk from here https://github.com/facebook/facebook-php-sdk/downloads
Open the /src folder and copy the 3 files(facebook.php abd
base_facebook.php and fb_ca_chain_bundle) to the /inc folder of your project
And that’s it
Download the facebook php sdk from github
Open the /src folder and copy the 3 files(facebook.php abd
base_facebook.php and fb_ca_chain_bundle) to the /inc folder of your project
And that’s it!
The code works, but he does not return the data from Facebook (name and email).
What can you do?
I have three files folder INC Facebook.
According to my testing: AJAX code returns EROR (function AjaxResponse).
What can you do?
Thank you
There is a problem in the code:
I want to make the connection button on some pages page.
And it only works on INDEX. And any other page …
You can make it work well in other pages (all pages on the site – for example)?
Thank you
is there an easy way to add a redirect to this script?
how to get the birth date from your script
You need “user_birthday” permission.
Hi, First this is a helpful toturial
everything works fine but my problem is i don’t get nothing into my database, what can i do for this, is there a solution, please i need some help.
Please check MySQL insert http://j.mp/YeVj1U
This is cool, and I used it in my application. But it is not working in IE 10. And your demo (http://www.saaraan.com/assets/ajax-facebook-connect/) is also not working in IE 10