Facebook log in is a convenient way to integrate the login system on the website. Through Facebook login, users can log into the web application with their Facebook account without registering on your website. Facebook provides you with a lot of SDK or API to log in with Facebook functionality on the site. However, the Facebook SDK for JavaScript is the most user-friendly way to integrate Facebook login to a web page.
Facebook JavaScript SDK permits the user to sign in to your website with their Facebook credentials. Using JavaScript SDK, you can implement a user login system with a Facebook account on a single page without page refresh.
In this tutorial, we will authorize the user with Facebook login credentials and obtain user profile data from Facebook using the JavaScript SDK. And how to integrate Facebook login with PHP SDK in a web application. Also, how to implement login with Facebook using JavaScript SDK. And store Facebook profile data in a database using jQuery, Ajax, PHP, and MySQL.
Before we begin to implement Facebook login with JavaScript API on the website, you need the Facebook App ID, which you can create on the Facebook App Dashboard.
JavaScript Code
In JavaScript, all you need to do is specify your Facebook app ID in FB.init({});
- fbLogin() opens a login dialogue to log in with Facebook credentials.
- getFbUserData() attach the user profile data from Facebook and display profile details and login status to the user.
- blog out() 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 : '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
You can use the following HTML to display the Facebook Login button, user profile details, and login status.
<!-- 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, PHP, Ajax, and MySQL)
After logging in via the Facebook JavaScript SDK, if you want to store user profile information in the MySQL database, follow the steps given below.
Database Table Creation
Make a table called users in a database to store information about the user’s profile.
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 DEFAULT NULL, `locale` varchar(10) COLLATE utf8_unicode_ci DEFAULT 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 will 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.
Firstly, the jQuery library needs to be loaded.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Secondly, 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; }); }
And lastly, Call the saveUserData()
function ingetFbUserData()
function and put the response data. After inserting thegetFbUserData()
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 a 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 user’s 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); } } ?>
Also, read our previous blog- Login with Google Account using PHP