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.
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.
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>
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.
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).
<?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
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Working wonderful ,thank you very much
Very Nice
Thanks
Such a nice detail post,
I have used in my recent project, it worked fine.
Hi, I’m interested in implementing the Facebook login on my website where I have problems is to request the permissions on Facebook I ask for video captures as I will use the permissions I do not know what to place in that area I would like your help thanks
thank you!
this helped me a lot
Thank you
Hello,
How can I save user’s information in session
and manipulate these data throught the whole website
Thanks
See this tutorial, it will help you to save and access the user’s information with SESSION – https://www.codexworld.com/codeigniter-autocomplete-textbox-using-jquery-ui/
i need to fetch user phone and birthday then?
Thank you very much codexworld! You saved my weekend! After hours of trying to make Facebook Login SDK work I finally came here and found the solution. I also asked them to extend the functionality of the script to get information about birthday and location and they helped me in few hours for a very honest $ pay. Affordable and reliable help, very suggested!
I have been trying for YEARS to get a Facebook Login onto my website without success.
It seems that the official documentation is written for Facebook employees ONLY and when you start to work your way through one of their (CRAPPY) examples, each section seems to be applicable to a different version of the API than the previous section.
If you Google it, all you get is a bunch of idiots trying to tell you how to use the Facebook code and when you try it, IT FAILS !!!
Your scripting worked straight out of the box!!!
CONGRATULATIONS AND MANY THANKS…
Thks!
I wonderd how i can get users likes?
Just adding likes to the fields part does not work..
thank you! great contribution! All the positive vibes 😀
super thank you super script
i want to logout from facebook on page refresh so how can i do that?