Implementing Facebook Login using JavaScript

Facebook Login is the fastest way to signup people into your website. Implementing this would make the user part of signing up for your website easier. This post will show you how to implement Facebook Login in your website using the Facebook JS SDK.

Creating App

The first and foremost thing to do to implement Facebook Login is to create a Facebook App. Once you have created an app you will be provided with,

  • App ID – Unique ID that Facebook uses to identify you application.
  • App Secret – App secret is used when making server side calls to Facebook.

Adding Domains

Once you have created your Facebook app, visit the app Settings page. In the App Domains text box add the domain to which the app must be available to.

Click on the Add Platform button and provide your website url and save the changes.

Add Domains

Facebook JS SDK

Use the following code snippet to load the Facebook JS SDK into your webpage.

<script type="text/javascript">
  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.2' // use version 2.2
   FB.getLoginStatus(function(response) {

  // 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'));

Paste this code immediately after the body tag.


The markup is pretty much simple, create two buttons for Login and Logout and attach click event listeners to those buttons for their respective actions.

<p><a id="facebookLogin" class="btn btn-primary btn-lg btn-facebook" onclick="loginUsingFacebook(); return false;" href="#" role="button">Facebook</a></p>
<p><a id="facebookLogout" style="display:none;" class="btn btn-warning btn-lg btn-facebook" onclick="logoutFacebook(); return false;" href="#" role="button">Logout</a></p>

Here i have used a tags in place of the buttons. But you have other ways to implement this behavior using other tags.


In the JavaScript file there are some functions and an App Object. The functions mostly aid in Facebook Login process while the App contains methods that is specific to the application which implements the server side operation of storing user details.

 * This is called whenever there is change in the user login status
 * @param response - The response from facebook login 
function statusChangeCallback(response) {
  var fbLogin = document.getElementById('facebookLogin'),
    fbLogout = document.getElementById('facebookLogout'),
    greet = document.getElementById('userGreeting'),
    fbStatus = document.getElementById('status');

  if (response.status === 'connected') {
    // Logged into your app and Facebook. = 'none'; = 'inline';
    fbStatus.innerHTML = 'Login successful';
    // Send user data if not logged in already.
    if (localStorage.getItem('app_social_uid') === '') {
      // Send the user data to the server.
  } else if (response.status === 'not_authorized') {
    // The person is logged into Facebook, but not your app.
    fbStatus.innerHTML = 'Please log into this app.';
    greet.innerHTML = '';
  } else {
    // The person is not logged into Facebook, so we're not sure if
    // they are logged into this app or not. = 'inline'; = 'none';
    greet.innerHTML = '';
    fbStatus.innerHTML = 'Login Using';

This method is called whenever there is a status change in the user authentication. Inside the method there are some DOM elements modified based on the status response.

The status from the response can be either,

  • connected – The user is logged in to Facebook and your app.
  • not_authorized – The user has not logged in to your app and has not authorized.

If the status is not either of the above, we assume the user is not logged into Facebook.

Here we store the user id in browser localStorage with the key app_social_uid. For this to work the browser must support localStorage.

If the user is connected we send the login status to the application backend using the App.sendUserData() method.

 * Check status and show the login dialog
function loginUsingFacebook() {
  FB.login(function(response) {
    FB.getLoginStatus(function(response) {
  }, {scope: 'public_profile, email'});

loginUsingFacebook function is attached to the Login button and triggers the Login Dialog once clicked on it using the FB.login() method. The method takes an object as a second param in which we can provide the scope required by the application for the user to approve. Here the public_profile and email of the user is requested.

 * Logout of facebook
function logoutFacebook() {
  FB.logout(function(response) {
    FB.getLoginStatus(function(response) {

logoutFacebook function is attached to the Logout button. When clicked this will request the facebook server to logout the user using FB.logout() method. App.logout() method is used to invalidate the user session in the application backend.

var App = {
   * Greet the user with a message
  greetUser: function() {
    FB.api('/me', function(data) {
      var greet = document.getElementById('userGreeting'),
      msg = 'Welcome ' + + '.';
      if (typeof !== 'undefined') {
        msg += ' Your email id is ' +;
      greet.innerHTML = msg;

   * Sends the user data to the server side.
  sendUserData: function() {
    FB.api('/me', function(data) {
      data['authResponse'] = FB.getAuthResponse();
      data['provider'] = 'Facebook';
      data['status'] = 'connected';
      // Store user id for invalidating session later
      localStorage.setItem('app_social_uid', data['id']);
      // Send the user data to the server
        method: 'post',
        url: 'ajax/user_data.php',
        data: data,
        dataType: 'json',
        success: function(data, status) {
          console.log('Sent User data!');
        error: function(error) {
          console.log('Error in sending ajax data');

The App is specific to the application that implements the Facebook Login. It handles the process of sending the user details to the application backend. The methods use the FB.api() to require information about the logged in user.

At backend of your application you can implement ways to store the various social logins available for users to login to your site.

Table Schema

-- Table structure for table `login`
  `id` int(10) unsigned NOT NULL,
  `user_id` bigint(10) unsigned NOT NULL,
  `name` varchar(64) CHARACTER SET utf8 NOT NULL,
  `email` varchar(256) CHARACTER SET utf8 DEFAULT NULL,
  `access_token` varchar(512) CHARACTER SET utf8 DEFAULT NULL,
  `provider` varchar(64) CHARACTER SET utf8 NOT NULL

-- Indexes for table `login`
 ADD PRIMARY KEY (`id`), ADD KEY `user_id` (`user_id`);

-- AUTO_INCREMENT for table `login`
MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT;

You can use the above database schema to implement other social logins and also modify it to your need. Here we just implement only the Facebook Login.


class App {
   * Holds the database connection
  private $mysqli;

   * Initializes the database connection.
   * @return Boolean
  public function __construct() {
    $this->mysqli = new mysqli(
      'localhost', 'demos.codedodle', 'demos.codedodle', 'fb');

    if ($this->mysqli->connect_errno) {
      return false;

   * Add the user data into the table
   * @param Int $id - Unique user id in the service provider
   * @param String $name - Username
   * @param String $status - Current login status of the user
   * @param String $access_token - Access token used to send request to
   *      service provider
   * @param String $provider - Service provider
   * @param String $email - Email id of the user
  public function addUserData(
        $id, $name, $email, $access_token, $provider
    ) {
    $cName = $this->mysqli->real_escape_string($name);
    $cEmail = $this->mysqli->real_escape_string($email);
    $cAccessToken = $this->mysqli->real_escape_string($access_token);

    $query = 'INSERT INTO `login` ' . 
        '(`user_id`, `name`, `email`, `access_token`, `provider`)'
        . 'VALUES ('. $id .', "'. $cName .'", "'. $cEmail .'", "'
        . $cAccessToken .'", "'. $provider . '")';
    $result = $this->mysqli->query($query);
    return $result ? $this->mysqli->affected_rows : false;

   * Check if the user is already available
   * @param Int $id - The unique user id form the service provider
   * @param String $provider - The login service provider
  public function isUserAvailable($id, $provider) {
    $result = $this->mysqli->query(
      'SELECT * FROM `login` WHERE `user_id` = ' . $id . ' AND `provider` = "'
      . $provider . '"'

    return $result ? $result->fetch_assoc() : false;

  public function __destruct() {

This class implements methods that the ajax calls use to check if a User is Available and Insert User Data.


 * @var array List of Login Service Providers
$providers = array(

// Facebook App id
$fb_app_id = 'your_app_id';


When called using ajax, this script will store the user details.

include_once '../config.php';
include_once 'App.php';

 * Store the following user data

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST)) {
  $valid_status = array('connected', 'not_authorized');

  $id = isset($_POST['id']) ? $_POST['id'] : '';
  $name = isset($_POST['name']) ? $_POST['name'] : '';
  $email = isset($_POST['email']) ? $_POST['email'] : '';

  $status = 0;
  if (isset($_POST['status']) && in_array($_POST['status'], $valid_status)) {
    $status = $_POST['status'] == 'connected' ? 1 : 0;

  $access_token = '';
  if (isset($_POST['authResponse']) && 
    isset($_POST['authResponse']['accessToken'])) {
    $access_token = $_POST['authResponse']['accessToken'];

  $provider = isset($_POST['provider']) && 
      in_array($_POST['provider'], $providers) ? $_POST['provider'] : '';

  if ($id) {
    $app = new App();
    $user = $app->isUserAvailable($id, $provider);
    if (!empty($user)) {
      // Add the user data to the database
      $result = $app->addUserData($id, $name, $email, $status, $access_token, 

Know that the server side implementation shown here is just an overview. This is just to show you how it can be done.

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,