Login with Facebook using JavaScript SDK

Facebook Login is the easiest way to integrate the login system on the website. Facebook Login allows users to log into the web application with their Facebook account without registration on your website. Facebook provides various SDK or API to Login with Facebook functionality on the website. But Facebook SDK for JavaScript is the most user-friendly way to integrate Facebook Login on the web page.

Facebook JavaScript SDK allows the user to sign-in to your website with their Facebook credentials. Using JavaScript SDK, you can implement the user login system 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.

Our earlier Facebook API tutorial showed how to integrate Facebook Login with PHP SDK in a web application. In this tutorial, we’ll show you how to implement Login with Facebook using JavaScript SDK and store Facebook profile data in the database using jQuery, Ajax, PHP, and MySQL.

Create Facebook App

Facebook App ID is required to use JavaScript SDK on the web application. Before getting started to implement Facebook Login with JavaScript API on the website, create an App on Facebook Developer Dashboard.

Facebook Login with JavaScript

JavScript Code:
The following code initializes the JavaScript SDK to integrate the Facebook Login API.

  • FB.init() – Specify Facebook App ID (appId) and other SDK configurations.
  • FB.getLoginStatus() – Check whether the user already logged in.
  • fbLogin() – Open a login dialog to login with Facebook account credentials.
  • getFbUserData() – Fetch the user’s account data from Facebook and display profile info 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      : 'InsertYourFacebookAppId', // FB App ID
      cookie     : true,  // enable cookies to allow the server to access the session
      xfbml      : true,  // parse social plugins on this page
      version    : 'v3.2' // 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 = '<p>Thanks for logging in, ' + response.first_name + '!</p>';
        document.getElementById('userData').innerHTML = '<h2>Facebook Profile Details</h2><p><img src="'+response.picture.data.url+'"/></p><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>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="images/fb-login-btn.png"/>';
        document.getElementById('userData').innerHTML = '';
        document.getElementById('status').innerHTML = '<p>You have successfully logout from Facebook.</p>';
    });
}
</script>

HTML Code:
Define the HTML elements to display Facebook Login button, status message, and user’s profile information on the web page.

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

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

<!-- Display user's profile info -->
<div class="ac-data" id="userData"></div>

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

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

Create Database Table:
To store the profile information a table is required in the database. The following SQL creates a users table in the MySQL database.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `oauth_provider` enum('facebook','google','twitter','') COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
 `oauth_uid` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `gender` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
 `picture` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
 `link` varchar(100) 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 Code:
We’ll use jQuery and Ajax to send the user’s profile data to the server-side script to insert the user data into the database with PHP and MySQL.

At first include the jQuery library.

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

The following saveUserData() function post the account data to server-side script (userData.php) using Ajax $.post() method.

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

Now call the saveUserData() function from getFbUserData() function and pass the response data. After modification, the updated getFbUserData() function will look like the below.

// 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 = '<p>Thanks for logging in, ' + response.first_name + '!</p>';
        document.getElementById('userData').innerHTML = '<h2>Facebook Profile Details</h2><p><img src="'+response.picture.data.url+'"/></p><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>FB Profile:</b> <a target="_blank" href="'+response.link+'">click to view profile</a></p>';
		
        // Save user data
        saveUserData(response);
    });
}

PHP Code:

Database Configuration (dbConfig.php)
This file helps to connect and select the database using PHP and MySQL.

<?php 
// Database configuration
$dbHost     "localhost";
$dbUsername "root";
$dbPassword "root";
$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);
}
?>

Insert/Update Data in Database (userData.php)
This file handles the database related operations (insert/update).

  • Retrieve POST data and convert JSON to PHP array.
  • Check whether user data already exists in the database.
    • If the user already exists, update data in the database.
    • If new a user, insert data to the database.
<?php 
// Load the database configuration file
include 'dbConfig.php';

// Retrieve POST data and convert JSON to PHP array
$userData json_decode($_POST['userData']);

if(!empty(
$userData)){
    
$oauth_provider $_POST['oauth_provider'];
    
$link = !empty($userData->link)?$userData->link:'';
    
$gender = !empty($userData->gender)?$userData->gender:'';
    
    
// Check whether user data already exists in database
    
$prevQuery "SELECT id 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 = '".$gender."', picture = '".$userData->picture->data->url."', link = '".$link."', modified = NOW() 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 = '".$gender."', picture = '".$userData->picture->data->url."', link = '".$link."', created = NOW(), modified = NOW()";
        
$insert $db->query($query);
    }
}
?>

Login with Google Account using JavaScript

Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request

If you have any questions about this script, submit it to our QA community - Ask Question

15 Comments

  1. Abubaker Hmd Said...
  2. Rodolfo Lopez Said...
  3. Ankur Jain Said...
  4. Gerardo Said...
  5. Phil Said...
  6. Toki Said...
  7. Fab Said...
  8. Devendra Said...
  9. Andrea De Donatis Said...
  10. Aubrey Said...
  11. Rens Said...
  12. Diegol Said...
  13. Valentin Said...
  14. Sameer Said...

Leave a reply

keyboard_double_arrow_up