Login with Facebook using JavaScript SDK Tutorial
Introduction
In this tutorial, you will learn how to Implement a Login with Facebook Feature in your web applications using Facebook SDK for JavaScript. The tutorial aims to provide a reference for IT/CS students and new programmers for learning and implementing a web OAuth Login using Facebook. Here, snippets are provided and a sample source code file is provided and free to download.
Getting Started
In this tutorial, we will use XAMPP software to run an Apache Server on our local machine. The interface snippets use CDNs for loading the external libraries (Bootstrap and jQUery) on the application. Please make sure to be connected to the internet in order to run the snippets properly.
Before we start on the coding part, we will create an Application on Facebook First. To do that, kindly follow the instructions below.
Creating a Facebook
- Open your preferred browser and browse the Facebook Developers Apps Page
- Next, click the "Create App" button
- Since this is just a test, select "None" as the App's Type Options.
- Next, fill in the required inputs on the basic information about your App.
- After your App has been successfully created, click the "Set up" button of the Facebook Login Product on the dashboard page.
- Next, select the "WWW" option.
- Next, enter your site's URL and save it.
- Then, on the page sidebar, you can see the "Facebook Login" dropdown menu and select settings. After the page redirects to the settings page, toggle the "Login with JavaScript SDK" to yes and enter your site's domain. Save the settings.
Creating the Authentication Checker
After creating an App on Facebook for Developers, let's create the Authentication Checker File of the sample page. On your source code folder in htdocs, create a new PHP file and save it as auth.php
Creating the Login Page Interface
Next, create a new PHP file and save it as index.php
- <?php require_once('auth.php') ?>
- <?php
- if(isset($_GET['logout'])){
- session_destroy();
- header('location: login.php');
- }
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
- </head>
- <body>
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
- <div class="container">
- <div>
- </div>
- </div>
- </nav>
- <div class="container my-5">
- <div class="row">
- <div class="col-lg-5 col-md-7 col-sm-12 mx-auto">
- <div class="card rounded-0">
- <div class="card-body">
- <div class="container-fluid">
- <hr>
- <div class="text-center">
- <img src="<?= $_SESSION['fb_profile_pic'] ?>" alt="" class="img-thumb-nail rounded-circle">
- </div>
- <dl>
- </dl>
- <hr>
- <div class="text-center">
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
Creating the Sign-in Script
Next, let's create the PHP Script that saves the logged-in user data on the session. Save the file as sign-in.php
- <?php
- if($_SERVER['REQUEST_METHOD'] == 'POST'){
- foreach($_POST as $k => $v){
- if($k=='picture')
- $_SESSION['fb_profile_pic'] = $v['data']['url'];
- else
- $_SESSION['fb_'.$k] = $v;
- }
- }else{
- }
- ?>
Creating the Home Page Interface
The snippet below is the script that contains the HTML elements and PHP Scripts for displaying the data of the logged-in user using Facebook. Save the file as index.php.
- <?php require_once('auth.php') ?>
- <?php
- if(isset($_GET['logout'])){
- session_destroy();
- header('location: login.php');
- }
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
- </head>
- <body>
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
- <div class="container">
- <div>
- </div>
- </div>
- </nav>
- <div class="container my-5">
- <div class="row">
- <div class="col-lg-5 col-md-7 col-sm-12 mx-auto">
- <div class="card rounded-0">
- <div class="card-body">
- <div class="container-fluid">
- <hr>
- <div class="text-center">
- <img src="<?= $_SESSION['fb_profile_pic'] ?>" alt="" class="img-thumb-nail rounded-circle">
- </div>
- <dl>
- </dl>
- <hr>
- <div class="text-center">
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
Creating the Logout Script
Next, create the PHP Script that destroys the session data upon logging out. Save the snippet below as logout.php.
- <?php
- foreach($_SESSION as $k => $v){
- }
Creating the JavaScript
Lastly, let's create the JavaScript codes that initiate the Facebook login button, login event listener, and logout event listener, and include the Facebook SDK for JavaScript. In my case, I save this file inside the fb-login directory and named the file as fb-login.php. This file is loaded both in index.php and login.php.
- var logout_btn = document.getElementById('logout_btn')
- window.fbAsyncInit = function() {
- FB.init({
- appId : '{app-ID}', // Change this with your Created App ID
- cookie : true,
- xfbml : true,
- version : 'v2.7'
- });
- FB.AppEvents.logPageView();
- /**
- * Check Login Status
- */
- FB.getLoginStatus(function(response) {
- fbStatusChange(response);
- });
- };
- (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 = "https://connect.facebook.net/en_US/sdk.js";
- fjs.parentNode.insertBefore(js, fjs);
- }(document, 'script', 'facebook-jssdk'));
- /**
- * After Login
- */
- function fbLogin(){
- FB.login(function(response){
- fbStatusChange(response)
- })
- }
- /**
- * Save FB User Data to Session
- */
- function fbStatusChange(loginResp){
- console.log(loginResp)
- if(loginResp.status =='connected' && (location.origin + location.pathname) == 'https://localhost/js-fb-login/login.php'){
- FB.api('/me', 'GET', {fields: 'email,name,gender,picture{url}' }, function(response) {
- if(!response.error){
- $.ajax({
- url:'sign-in.php',
- method:"POST",
- data: response,
- dataType:"JSON",
- error:function(err){
- alert("Login Failed!")
- console.error(err)
- },
- success:function(resp){
- if(resp.status == 'success'){
- location.replace('index.php');
- }else{
- alert("Login Failed!")
- }
- }
- })
- }else{
- alert("Login Failed!")
- console.error(response.error)
- }
- });
- }
- }
- /**
- * Logout Facebook
- */
- if(logout_btn !== undefined && logout_btn !== null){
- logout_btn.addEventListener('click', function(e){
- e.preventDefault()
- FB.logout(function(){
- console.log('Facebook Account has been logged out to this application.')
- })
- location.replace(this.getAttribute('href'))
- })
- }
That's it! You can now test the source code that we created and see if works as we plan.
Application Snapshots
Here are some snapshots of the application.
Login Button
Home Page
That's the end of this tutorial. I have also provided the source code file that I created for this tutorial. you can download it by clicking the Download button located after this article. I hope this Login with Facebook using JavaScript SDK Tutorial helps you with what you are looking for and that you'll find this useful for your current and future web application projects.
Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding :)
Add new comment
- 529 views