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
123456789101112131415

<?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
12

<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
123

<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
123456789101112131415161718192021222324

<?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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253

<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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182

<?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']) &#038;&#038; 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 :<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 :Hi '. $me['first_name'] . ' '. $me['last_name'].' ('.$uid.')!  Now that you are logged in to Facebook using jQuery Ajax [<a href="'.$return_url.'?logout=1">Log Out</a>].
		the information can be stored in database ';
		//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

  • 64 Comments

    Add Comment
    • Karan
      it working thank you so much
    • Rajnish
      Your demo is not working.
    • Kiran
      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 ?
    • Cem
      hi I am install when login You must allow us to access your email id! how to fix please help thank you
    • Faizan
      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
    • Willian Santana
      Hello to work properly I had to perform these alterations . I hope it helps. // line 58-71, index.php LodingAnimate(); //Animate login // Declare permission upstream js FB.api('/me', {fields: 'name, email'}, 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(); } }); // line 18-29, process_facebook.php if ($fbuser) { try { // Proceed knowing you have a logged in user who's authenticated. // Declare permission upstream php $me = $facebook->api('/me?fields=id,first_name,last_name,email,gender,locale,picture'); $uid = $facebook->getUser(); } catch (FacebookApiException $e) { //echo error_log($e); $fbuser = null; } }
    • Faizan
      Hi,I was working with your "ajax-facebook-connect-with-jquery" and it was working great as i want but now its giving an error that var FB is not defined so can u please help me to solve this error.Thanks
    • Faizan
      It is a great script thanx for this, but i m getting a problem when i try to login with faccebook after loading an error pops up that "You must allow us to access your email id!" can anyone help me to solve this plzzz
    • SimiaoFernandes
      Hi... The example works fine, but the return is just id and name. Could You tell me what you still need to setup? Thanks a lot!
    • Ed
      Is it possible to use this script on a http and have the authentication code on a https and then send the data back to the http. Why do this? So we don't have to buy and ssl for each domain name as Facebook requires an ssl. Thanks