0% found this document useful (0 votes)
47 views1 page

Login With Facebook Using JavaScript SDK - CodexWorld

This tutorial provides a detailed guide on how to implement Facebook Login using the JavaScript SDK, allowing users to log into a web application with their Facebook credentials without needing to register. It includes JavaScript code for authentication, fetching user profile data, and storing this data in a MySQL database using jQuery, Ajax, and PHP. The tutorial also covers the necessary setup for creating a Facebook App ID and managing user data in the database.

Uploaded by

nico.glez.1976
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views1 page

Login With Facebook Using JavaScript SDK - CodexWorld

This tutorial provides a detailed guide on how to implement Facebook Login using the JavaScript SDK, allowing users to log into a web application with their Facebook credentials without needing to register. It includes JavaScript code for authentication, fetching user profile data, and storing this data in a MySQL database using jQuery, Ajax, and PHP. The tutorial also covers the necessary setup for creating a Facebook App ID and managing user data in the database.

Uploaded by

nico.glez.1976
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

TUTORIALS HOW TO DEMOS SCRIPTS DEALS SERVICES WEB TOOLS Search tutorials 

Home » JavaScript » Login with Facebook using JavaScript SDK

SUBSCRIBE FOR FREE NEWSLETTER


Login with Facebook using JavaScript SDK Join our 75,000+ subscribers and get the latest tutorials and resources, straight to
your inbox.

By: CodexWorld In: JavaScript Last Updated: Jul 26, 2018 Share Tweet
ENTER YOUR EMAIL...

Login with Facebook using JavaScript SDK SUBSCRIBE

Hire Us @ Low Cost

TRENDING TUTORIALS

Login with Facebook using PHP

Login with Google Account using PHP

PayPal Standard Payment Gateway Integration in PHP

Autocomplete Textbox using jQuery, PHP and MySQL

Drag and Drop Reorder Images using jQuery, Ajax, PHP & MySQL

Using new Google reCAPTCHA with PHP

Upload Multiple Images using jQuery, Ajax and PHP

Facebook Login is the easiest way to integrate login system in the website. Facebook Login allows users to log into the web application with their Facebook account CodeIgniter Tutorial for Beginners

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 into your website with their Facebook credentials. Using JavaScript SDK, you can implement 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
Premium Script: PHP social login system - Facebook, Google, and Twitter login in a single script. Download Now
pro le data from Facebook using JavaScript SDK. TOPICS all topics

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 PHP CodeIgniter
Login with Facebook using JavaScript SDK and store Facebook pro le data in the database using jQuery, Ajax, PHP, and MySQL.
WordPress JavaScript
Before get started to implement Facebook Login with JavaScript API on the website, you need a Facebook App ID which can be created on Facebook App
Drupal GoogleMap
Dashboard.
HTML&CSS CakePHP
Are you want a detailed guide to creating Facebook App ID? Follow this step-by-step tutorial – How to Create Facebook App, App ID, and App Secret
Bootstrap Web Development

JavaScript Code PayPal GoogleAPI

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 pro le data from Facebook and display pro le details and login status to the user.
LATEST HOW TO GUIDES

fbLogout() logout the user from their Facebook account. How to Get Selected Checkboxes Value using jQuery

<script> How to Remove Special Characters from String in PHP


window.fbAsyncInit = function() {
// FB JavaScript SDK configuration and setup How to Check if a String Contains a Speci c Word or Substring in PHP
FB.init({
appId : 'InsertYourFacebookAppId', // FB App ID How to Convert File Size to Human Readable Format in PHP
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse social plugins on this page How to Check Website Availability with PHP
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 pro le 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 pro le information into the MySQL database, follow the below steps.

Database Table Creation


Create a table called users in a database to store the pro le 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 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’ll use jQuery and Ajax to send the user pro le data to the PHP script ( userData.php ) for inserting the user data into the MySQL database.
At rst jQuery library need to be loaded.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/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);
});
}

dbCon g.php
This le 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 rst, 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."', gende
r = '".$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."', pictur
e = '".$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);
}
}
?>

SEE ALSO: Login with Facebook using PHP

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

 Download Source Code  View Demo

Previous Next
 Ajax Pagination with Search and Creating a Custom 404 Error Page 

Filter in CodeIgniter in WordPress

RECOMMENDED TUTORIALS FOR YOU

10 Comments

Toki Said...

Thank you

June 10, 2018 at 3:35 PM

Fab Said...

Hello,

How can I save user’s information in session


and manipulate these data throught the whole website

Thanks

May 14, 2018 at 8:56 PM

CodexWorld Said...

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/

May 15, 2018 at 6:10 PM

Devendra Said...

i need to fetch user phone and birthday then?

February 28, 2018 at 12:46 PM

Andrea De Donatis Said...

Thank you very much codexworld! You saved my weekend! After hours of trying to make Facebook Login SDK work I nally 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. A ordable and reliable help, very
suggested!

January 11, 2018 at 10:05 PM

Aubrey Said...

I have been trying for YEARS to get a Facebook Login onto my website without success.
It seems that the o cial 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 di erent 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…

August 29, 2017 at 5:47 PM

Rens Said...

Thks!

I wonderd how i can get users likes?

Just adding likes to the elds part does not work..

May 26, 2017 at 2:22 PM

Diegol Said...

thank you! great contribution! All the positive vibes

April 22, 2017 at 6:09 PM

Valentin Said...

super thank you super script

April 21, 2017 at 7:22 PM

Sameer Said...

i want to logout from facebook on page refresh so how can i do that?

April 18, 2017 at 7:36 AM

Leave a reply

Comment *

Your Name * Your Email * Your Website

Post Comment

Copyright © 2018 CodexWorld. All rights reserved. About Us | Privacy Policy | Terms & Conditions | Write For Us | Advertise | Contact

You might also like