Last week one of my reader asked me that how to Implement Facebook oAuth Login with Javascript SDK without Page Refresh and also data should be store on MYSQL server as well. So I thought this is the time to write a tutorial for this.

Facebook has several login methods based on the devices like iOS, Android and Web. Here we are going to Implement this Facebook oAuth login system for Website. Millions of Websites and Apps are implemented Facebook Login into their sites to increase the registrations. I hope this simple tutorial will help you to implement in your PHP web based projects 🙂

Facebook oAuth Login system

View Live Demo & Download

Step 1 – Creating Facebook App

We need to create an Facebook App to get the App ID and App Secret Key

Goto and Click Add a New App

create facebook app


In the popup – click website

choose-websiteNow Click Skip Quick Test 


You need to Choose Name for your App and Click Create App ID


Step 2 – App Settings

Under settings, Provide values for App domain ( Eg: ) and Contact Email and click Save Changes. And Provide Values for Site URL and Mobile site URL ( Its Optional )


Step 3 – Making App Live

Now under Status & Review, Click the button to make you App live after you implemented the FB login in your project. In the meantime you can use your email ID for development/testing purposes


After creating the app, Please create the table called tbl_users in your database

  `fld_user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `fld_facebook_id` varchar(100) NOT NULL,
  `fld_user_name` varchar(60) NOT NULL,
  `fld_user_email` varchar(60) DEFAULT NULL,
  `fld_user_doj` int(10) NOT NULL,
  PRIMARY KEY (`fld_user_id`)

Facebook Javascript SDK

Please the below code on before body tag. The below script will load the SDK asynchronously

  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); = id;
    js.src = "//";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

Now we need to initialize the facebook javascript SDK

window.fbAsyncInit = function() {
      appId      : 'your app ID',
      cookie     : true,  // enable cookies to allow the server to access 
                          // the session
      xfbml      : true,  // parse social plugins on this page
      version    : 'v2.3' // use version 2.3

    FB.getLoginStatus(function(response) {

In the above code, the FB.getLoginStatus function allows you to determine if a user is logged in to Facebook and has authenticated your app. There are three possible states for a user:

  1. the user is logged into Facebook and has authenticated your application (connected)
  2. the user is logged into Facebook but has not authenticated your application (not_authorized)
  3. the user is not logged into Facebook at this time and so we don’t know if they’ve authenticated your application or not (unknown)

With social application, knowing which of the these three states the user is in is one of the first things your application needs to know upon page load.

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {

  if (response.status === 'connected') {
      // Logged into your app and Facebook.
      // we need to hide FB login button
      //fetch data from facebook
  } else if (response.status === 'not_authorized') {
      // The person is logged into Facebook, but not your app.
      $('#status').html('Please log into this app.');
  } else {
      // The person is not logged into Facebook, so we're not sure if
      // they are logged into this app or not.
      $('#status').html('Please log into facebook');

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample code below.
function checkLoginState() {
  FB.getLoginStatus(function(response) {

Facebook oAuth Login Call Function

The below code will be called after clicking the Login with Facebook button from the web app.

There is an optional scope parameter that can be passed along with the function call that is a comma separated list of permissions to request from the person using the app. Here’s how you would call FB.login() with the same scope as the Login Button we used below.

We need to call the FBLogin() while clicking the Login with Facebook button

function FBLogin()
      FB.login(function(response) {
         if (response.authResponse) 
             getUserInfo(); //Get User Information.
          } else
           alert('Authorization failed.');
       },{scope: 'public_profile,email'});

The below getUserInfo() will be called after successful login with facebook. We are now ready to call the FB API calls via FB.api() method.

Syntax of FB.api()

FB.api('/me', function(response) {

We need to pass the response to the php file where we can insert or update the user in our database.

function getUserInfo() {
    FB.api('/me', function(response) {
            type: "POST",
            dataType: 'json',
            data: response,
            url: 'check_user.php',
            success: function(msg) {
             if(msg.error== 1)
              alert('Something Went Wrong!');
             } else {
              $('#fbname').text("Name : ";
              $('#fbemail').text("Email : ";
              $('#fbfname').text("First Name : "+msg.first_name);
              $('#fblname').text("Last Name : "+msg.last_name);
              $('#fbid').text("Facebook ID : ";
              $('#fbimg').html("<img src='""/picture'>");


The above function will return the data in JSON format. We need to parse and display those datas.

Logout from Facebook

You can log people out of your app by attaching the JavaScript SDK function FB.logout to a button or a link, as follows:

  function FBLogout()
  	FB.logout(function(response) {
         $('#fblogin').show(); //showing login button again
         $('#fbstatus').hide(); //hiding the status

Below PHP code is used to update or insert the user in our database


if(isset($_POST['id']) && !empty($_POST['id']))
	include_once 'db.php';
	extract($_POST); // extract post variables

	//check if facebook ID already exits
	$check_user_query = "select * from tbl_users WHERE fld_facebook_id = $id";
	$check_user = $db->getDataFromQuery($check_user_query);
		//new user - we need to insert a record
		$time = time();
		$insert_user_query = "Insert into tbl_users (`fld_user_name`, `fld_user_email`, `fld_facebook_id`, `fld_user_doj`) VALUES ('$name', '$email', $id, $time)";
		$insert_user = $db->UpdateQuery($insert_user_query);
		echo json_encode($_POST);
	} else {
		$update_user_query = "update tbl_users set fld_user_name = '$name', fld_user_email='$email' WHERE fld_facebook_id = $id";
		$update_user = $db->UpdateQuery($update_user_query);
		echo json_encode($_POST);
} else {
	$arr = array('error' => 1);
	echo json_encode($arr);

Please dont forgot the check the live demo on Facebook oAuth Login with Ajax, PHP & MYSQL

Please subscribe to my blog to get the latest updates

View Live Demo & Download

Related Posts