Login with Facebook using JavaScript SDK


Facebook Login provides an easy way to integrate login system to your website. Facebook Login allow users to log into your website with their Facebook account without registration on your website. Our earlier tutorial has shown how to integrate Facebook Login with PHP in a web application. In this tutorial, we’ll provide a step-by-step guide to learn how to use Facebook JavaScript SDK for implementing login system in a web application.

Using JavaScript SDK, you can implement user login with Facebook account on a single page without page refresh. In this example script, we will authenticate the user with Facebook login credentials and fetch the user profile data from Facebook using JavaScript SDK.

Before get started to implement Facebook Login with JavaScript API, you need a Facebook App ID which can be created on Facebook App Dashboard.

Are you want get a detailed guide to creating Facebook App ID? Visit the below link.

JavScript Code

In JavaScript, you only need to specify your Facebook App ID in FB.init({});

  • fbLogin() opens a login dialog to log in with Facebook credentials.
  • getFbUserData() fetch the user profile data from Facebook and display profile details and login status to the user.
  • fbLogout() logout the user from their Facebook account.
<script>
window.fbAsyncInit = function() {
    // FB JavaScript SDK configuration and setup
    FB.init({
      appId      : 'IsertYourFacebookAppId', // 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.8' // use graph api version 2.8
    });
    
    // Check whether the user already logged in
    FB.getLoginStatus(function(response) {
        if (response.status === 'connected') {
            //display user data
            getFbUserData();
        }
    });
};

// 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 and display the user profile data
            getFbUserData();
        } else {
            document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
        }
    }, {scope: 'email'});
}

// Fetch the user profile data from facebook
function getFbUserData(){
    FB.api('/me', {locale: 'en_US', fields: 'id,first_name,last_name,email,link,gender,locale,picture'},
    function (response) {
        document.getElementById('fbLink').setAttribute("onclick","fbLogout()");
        document.getElementById('fbLink').innerHTML = 'Logout from Facebook';
        document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.first_name + '!';
        document.getElementById('userData').innerHTML = '<p><b>FB ID:</b> '+response.id+'</p><p><b>Name:</b> '+response.first_name+' '+response.last_name+'</p><p><b>Email:</b> '+response.email+'</p><p><b>Gender:</b> '+response.gender+'</p><p><b>Locale:</b> '+response.locale+'</p><p><b>Picture:</b> <img src="'+response.picture.data.url+'"/></p><p><b>FB Profile:</b> <a target="_blank" href="'+response.link+'">click to view profile</a></p>';
    });
}

// Logout from facebook
function fbLogout() {
    FB.logout(function() {
        document.getElementById('fbLink').setAttribute("onclick","fbLogin()");
        document.getElementById('fbLink').innerHTML = '<img src="fblogin.png"/>';
        document.getElementById('userData').innerHTML = '';
        document.getElementById('status').innerHTML = 'You have successfully logout from Facebook.';
    });
}
</script>

HTML Code

The following HTML is used to display Facebook Login button, login status, and user profile details.

<!-- Display login status -->
<div id="status"></div>

<!-- Facebook login or logout button -->
<a href="javascript:void(0);" onclick="fbLogin()" id="fbLink"><img src="fblogin.png"/></a>

<!-- Display user profile data -->
<div id="userData"></div>

Save User Data to Database (jQuery, Ajax, PHP and MySQL)

After user logged in via Facebook JavaScript SDK, if you want to store the user profile information into the MySQL database, follow the below steps.

Database Table Creation
Create a table called users in a database to store the profile information of the users.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `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,
 `gender` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
 `locale` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `picture` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

JavaScript
We’ll use jQuery and Ajax to send the user profile data to the PHP script (userData.php) for inserting the user data into the MySQL database.
At first jQuery library need to be loaded.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Add the saveUserData() function in the above JavaScript.

// Save user data to the database
function saveUserData(userData){
    $.post('userData.php', {oauth_provider:'facebook',userData: JSON.stringify(userData)}, function(data){ return true; });
}

Now call the saveUserData() function in getFbUserData() function and put the response data. After inserting, the getFbUserData() function will look like the below.

function getFbUserData(){
    FB.api('/me', {locale: 'en_US', fields: 'id,first_name,last_name,email,link,gender,locale,picture'},
    function (response) {
        document.getElementById('fbLink').setAttribute("onclick","fbLogout()");
        document.getElementById('fbLink').innerHTML = 'Logout from Facebook';
        document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.first_name + '!';
        document.getElementById('userData').innerHTML = '<p><b>FB ID:</b> '+response.id+'</p><p><b>Name:</b> '+response.first_name+' '+response.last_name+'</p><p><b>Email:</b> '+response.email+'</p><p><b>Gender:</b> '+response.gender+'</p><p><b>Locale:</b> '+response.locale+'</p><p><b>Picture:</b> <img src="'+response.picture.data.url+'"/></p><p><b>FB Profile:</b> <a target="_blank" href="'+response.link+'">click to view profile</a></p>';
        
        // Save user data
        saveUserData(response);
    });
}

dbConfig.php
This file helps to connect and select the database.

<?php
// Database configuration
$dbHost     "localhost";
$dbUsername "root";
$dbPassword "";
$dbName     "codexworld";

//Create connection and select DB
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

if (
$db->connect_error) {
    die(
"Unable to connect database: " $db->connect_error);
}
?>

userData.php
At first, JSON data would be decoded and stored into PHP variable ($userData). Based on oauth_provider and oauth_uid, we’ll check whether the user data already exists in the database and insert or update the user data into the users table.

<?php
//Load the database configuration file
include 'dbConfig.php';

//Convert JSON data into PHP variable
$userData json_decode($_POST['userData']);
if(!empty(
$userData)){
    
$oauth_provider $_POST['oauth_provider'];
    
//Check whether user data already exists in database
    
$prevQuery "SELECT * FROM users WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData->id."'";

    
$prevResult $db->query($prevQuery);
    if(
$prevResult->num_rows 0){ 
        
//Update user data if already exists
        
$query "UPDATE users SET first_name = '".$userData->first_name."', last_name = '".$userData->last_name."', email = '".$userData->email."', gender = '".$userData->gender."', locale = '".$userData->locale."', picture = '".$userData->picture->data->url."', link = '".$userData->link."', modified = '".date("Y-m-d H:i:s")."' WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData->id."'";
        
$update $db->query($query);
    }else{
        
//Insert user data
        
$query "INSERT INTO users SET oauth_provider = '".$oauth_provider."', oauth_uid = '".$userData->id."', first_name = '".$userData->first_name."', last_name = '".$userData->last_name."', email = '".$userData->email."', gender = '".$userData->gender."', locale = '".$userData->locale."', picture = '".$userData->picture->data->url."', link = '".$userData->link."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'";
        
$insert $db->query($query);
    }
}
?>

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You

4 Comments

  1. Rens Said...
  2. Diegol Said...
  3. Valentin Said...
  4. Sameer Said...

Leave a reply