Ajax Facebook Connect with jQuery & PHP

Implementing "Login with Facebook" using just their new PHP SDK is very easy, everything can be accomplished with minimal PHP code, but some of us may want to take it little further to create a nice looking Ajax based login system. Yes, with little bit of Javascript and Facebook PHP SDK, we can create Ajax based Facebook Login system.
Facebook has recently released PHP SDK version 4, you can read new article here about this SDK and how to implement it in projects like this.
I have created 4 files in this tutorial, first one is config.php, this file stores Facebook app ID, app SECRET and database information needed by other files. Second one is the index.php, front page for user interaction where visitors see Facebook Login button, from this page ajax requests will be sent to server. The process_facebook.php runs in the background connects to Facebook to fetch user data and inserts records in database. channel.php is included to improve communication speed in some older browsers as described here.

Create User Table

Run MySql query below in phpMyAdmin to create a table called "usertable", table contains 4 fields. id(Int, Auto Increment), fbid (BigInt, Facebook ID), fullname(Varchar, Full Name) and email(Varchar, Email).[cc lang="mysql"] 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; [/cc]

Configuration File

Create Facebook application and replace values in config.php file. Specify return URL and permissions required by your application.
PHP
  • 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_actions,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 ################################################################### ?>

Login Button

I have attached Javascript SDK in the page that comes with their login button plugin, but login button is not official, it was later created by myself using CSS and image because the error "FB.login called when user is already logged in" keeps appearing with official button when attaching CallAfterLogin() function to its onlogin attribute.
HTML
  • 1
<a href="#" rel="nofollow" class="fblogin-button" onClick="javascript:CallAfterLogin();return false;">Login with Facebook</a>
You can render their official button if you want, just by placing their HTML block once their JavaScript SDK is loaded in the page, just remember to add onlogin and scope attributes, onlogin attribute is required to attach our CallAfterLogin() function:
HTML
  • 1
<div class="fb-login-button" data-max-rows="1" data-size="medium" data-show-faces="false" data-auto-logout-link="false" onlogin="javascript:CallAfterLogin();" scope="publish_actions,email"></div>
To check whether user is logged in or not in this tutorial, I've created session variable called $_SESSION['logged_in'], if you are using some user management system in your website, you have to make appropriate changes here.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
<?php session_start(); include_once("config.php"); if(!isset($_SESSION['logged_in'])) { echo '<div id="results">'; echo '<!-- results will be placed here -->'; echo '</div>'; echo '<div id="LoginButton">'; echo '<a href="#" rel="nofollow" class="fblogin-button" onClick="javascript:CallAfterLogin();return false;">Login with Facebook</a>'; echo '</div>'; } else { echo 'Hi '. $_SESSION['user_name'].'! You are Logged in to facebook, <a href="?logout=1">Log Out</a>.'; } ?>
Here's the Javascript code.
JQUERY
  • 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
<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(); } }); } }, {scope:'<?php echo $fbPermissions; ?>'}); } //functions function AjaxResponse() { //Load data from the server and place the returned HTML into the matched element using jQuery Load(). $( "#results" ).load( "process_facebook.php" ); } //Show loading Image function LodingAnimate() { $("#LoginButton").hide(); //hide login button once user authorize the application $("#results").html('<img src="img/ajax-loader.gif" /> Please Wait Connecting...'); //show loading image while we process user } //Reset User button function ResetAnimate() { $("#LoginButton").show(); //Show login button $("#results").html(''); //reset element html } </script>

Process Requests

Once the Ajax request is made to process_facebook.php, it connects to Facebook and retrieves user details, and stores them in database table. Since we already have user session with JavaScript SDK, PHP-SDK should have no trouble using the Facebook session and APIs.
PHP
  • 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
<?php session_start(); include_once("config.php"); //Include configuration file. require_once('inc/facebook.php' ); //include fb sdk /* Detect HTTP_X_REQUESTED_WITH header sent by all recent browsers that support AJAX requests. */ if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) { //initialize facebook sdk $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 using mysqli */ $mysqli = new mysqli($hostname, $db_username, $db_password,$db_name); if ($mysqli->connect_error) { die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error); } //Check user id in our database $UserCount = $mysqli->query("SELECT COUNT(id) as usercount FROM usertable WHERE fbid=$uid")->fetch_object()->usercount; if($UserCount) { //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. $mysqli->query("INSERT INTO usertable (fbid, fullname, email) VALUES ($uid, '$fullname','$email')"); } $mysqli->close(); } 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 s/he clicks log-out link. */ $_SESSION['logged_in']=$loggedin; $_SESSION['user_name']=$user_name; } ?>
That's it! I am sure this will help you make your own Ajax Facebook Connect, Good luck.Download Demo
  • e.async = true;e.src = document.location.protocol +’//connect.facebook.net/en_US/all.js’; document.getElementById(‘fb-root’).appendChild(e);}());Not working in IE 10 .. any help in this ?
  • Hi thanx for your help but my problem was due to my own setted anti virus for my browsers to stop the sucking redirections of pages.I have got stucked like that i have setted the anti virus on all browsers and when i was checking on other browsers it was giving the same error like “reference FB is not defined” and then by chance i removed the anti virus from the browser and it works properly
New question is currently disabled!