Facebook login integration in website with pop up form using Javascript SDK

Posted by Admin on 18 April 2018 in Javascript/Jquery,Ajax,PHP

In this blog, I will show you how to integrate Facebook login our in website using javascript SDK. As we know that to access all the assets of any website we need to register with this website.Sometimes we need to fill length form with different fields like email id, first name, last name, password and confirm password and many more. It is also common that we need to verify our email which was given in registration form.So this is very lengthy and Headache process for every user. We simply register and login to any website using social media like facebook, google, twitter, LinkedIn and many more.We just need to click a social button and login with social media we automatically register and login to any website. We do not need to remember password also. 

In this article, we are going show you how to integrate facebook login with popup form using Javascript SDK.We will use login.php to login, dashboard.php which will be used as welcome screen after login, config.php which will use for database connectivity , loginverify.php to check we are login or not.If we are not login this loginverfiy.php will redirect on login page. logout.php will use for destroy session after destroying session we will redirect on login page. And most important files are process.php and custom.js. In custom.js we will define Javascript code and Facebook authentication code. In process.php we will register the user and set session. Steps are given below. In this project we are using free admin template AdminLte. You can download this template from https://adminlte.io/

Create Facebook App

step 1 :  First we need to create Facebook App. Login with your facebook account and go to https://developers.facebook.com/  and click Add a new App in My apps option which located in the menu section. A form will be open enter your app name in display name and your contact email id and click Create App ID. Captcha will be open enter captcha code. Your app will be created.

codex king 


Click on setup in facebook login product under Add a Product section to setup facebook login. And select Platform,we are using facebook login for web. We select web as a platform.


Codex king


Enter your site url eg: yoursite.com and click save and continue. Now go to Basic under Settings and enter App domains eg: yoursite.com, Privacy Policy URL, and select  category of your app. Finally at the end enable app status from Development to Live mode. You can also change status of app by going to App Review and set Make YOUR_APP_NAME to public.

Codex King


step 2 :  Create a database and define table :

  `oauth_provider` enum('','facebook','google','twitter') COLLATE utf8_unicode_ci NOT NULL,
  `oauth_uid` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `first_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `last_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `modified` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`)


 Step 3: Config.php

  define('DB_HOST', 'localhost');

  $conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
  if ($conn->connect_error) { 
	die("Connection failed: " . $conn->connect_error);


 Step 4: Create js  Folder and create file custom.js 

		window.fbAsyncInit = function() {
		    // FB JavaScript SDK configuration and setup
		      appId      : 'APP_ID', // FB App ID
		      cookie     : true,  // enable cookies to allow the server to access the session
		      xfbml      : true,  // parse social plugins on this page
		      version    : 'v2.11' // use graph api version 2.8

		// Load the JavaScript SDK asynchronously
		(function(d, s, id) {
		    var js, fjs = d.getElementsByTagName(s)[0];
		    if (d.getElementById(id)) return;
		    js = d.createElement(s); js.id = id;
		    js.src = "//connect.facebook.net/en_US/sdk.js";
		    fjs.parentNode.insertBefore(js, fjs);
		}(document, 'script', 'facebook-jssdk'));

// Facebook login with JavaScript SDK
function fbLogin()
    FB.login(function (response) {
        if (response.authResponse) 
            // Get  the user profile data
			FB.api('/me', {locale: 'en_US', fields: 
			function (userData)
                               {oauth_provider:'facebook',userData: JSON.stringify(userData),action:'1'}, 
				    window.location= "dashboard.php";	  	
				   alert('something goes wrong');
            //do something
    }, {scope: 'email'});


Step 5:  Login.php, In login.php facebook login image button and include custom.js (with jquery library if you do not include in page) in footer section or end of the page.  

<a href="javascript:void(0);" onclick="fbLogin();" >
        <img src="facebook_login_image.png" alt="Login with Facebook">

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="js/custom.js"></script>

Step 6: process.php

include_once 'config.php';   
switch ($_POST['action']) {
    case '1':
        echo '0';

function facebooklogin()
    global $conn;
    $userData = json_decode($_POST['userData']);
        $sql = "select * FROM  social_login WHERE email = '".$userData->email."'";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) 
            $row = $result->fetch_assoc();
            $_SESSION['user_id'] = $row['id'];
            $_SESSION['user_name'] = $row['first_name'].' '.$row['last_name'];  

            $oauth_provider = 'facebook';
            $oauth_uid = $userData->id;
            $email = $userData->email;
            $first_name = $userData->first_name;
            $last_name =   $userData->last_name;            
            $sql="insert into social_login(oauth_provider,oauth_uid,email,first_name,last_name) values('$oauth_provider','$oauth_uid','$email','$first_name','$last_name')";
            $id = mysqli_insert_id($conn);
            $_SESSION['user_id'] = $id;
            $_SESSION['user_name'] = $first_name.' '.$last_name;


        $status = 1;
        $status = 0;

      echo $status;



 Step 7: loginverify.php

	 echo '<script type="text/javascript">window.location="login.php";</script>';



Step 8: In dashboard.php, we only show include loginverify.php and config.php.

include_once 'config.php';
include_once "loginverify.php";

Step 9: logout.php

include_once 'config.php';

echo '<script type="text/javascript">window.location="login.php";</script>';



Note: According to Facebook March 2018 update, Facebook Login using Javascript SDK only work on https protocol.


To share this article on social media