Ajax Facebook Connect with jQuery & PHP

Implementing “Login with Facebook” using just their new PHP SDK is very easy, everything can be accomplished with minimal PHP code, but some of us may want to take it little further to create a nice looking Ajax based login system. Yes, with little bit of Javascript and Facebook PHP SDK, we can create Ajax based Facebook Login system.

Facebook has recently released PHP SDK version 4, you can read new article here about this SDK and how to implement it in projects like this.

I have created 4 files in this tutorial, first one is config.php, this file stores Facebook app ID, app SECRET and database information needed by other files. Second one is the index.php, front page for user interaction where visitors see Facebook Login button, from this page ajax requests will be sent to server. The process_facebook.php runs in the background connects to Facebook to fetch user data and inserts records in database. channel.php is included to improve communication speed in some older browsers as described here.

Create User Table

Run MySql query below in phpMyAdmin to create a table called “usertable“, table contains 4 fields. id(Int, Auto Increment), fbid (BigInt, Facebook ID), fullname(Varchar, Full Name) and email(Varchar, Email).

[cc lang=”mysql”]
CREATE TABLE IF NOT EXISTS `usertable` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`fbid` bigint(20) NOT NULL,
`fullname` varchar(60) NOT NULL,
`email` varchar(60) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
[/cc]

Configuration File

Create Facebook application and replace values in config.php file. Specify return URL and permissions required by your application.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
########## app ID and app SECRET (Replace with yours) #############
$appId = 'xxxxxx'; //Facebook App ID
$appSecret = 'xxxxxxxxxxxxxx'; // Facebook App Secret
$return_url = 'http://yoursite.com/connect_script/';  //path to script folder
$fbPermissions = 'publish_actions,email'; //more permissions : https://developers.facebook.com/docs/authentication/permissions/

########## MySql details (Replace with yours) #############
$db_username = "xxxxxx"; //Database Username
$db_password = "xxxxxx"; //Database Password
$hostname = "localhost"; //Mysql Hostname
$db_name = 'database_name'; //Database Name
###################################################################
?>

Login Button

I have attached Javascript SDK in the page that comes with their login button plugin, but login button is not official, it was later created by myself using CSS and image because the error “FB.login called when user is already logged in” keeps appearing with official button when attaching CallAfterLogin() function to its onlogin attribute.

1
<a href="#" rel="nofollow" class="fblogin-button" onClick="javascript:CallAfterLogin();return false;">Login with Facebook</a>

You can render their official button if you want, just by placing their HTML block once their JavaScript SDK is loaded in the page, just remember to add onlogin and scope attributes, onlogin attribute is required to attach our CallAfterLogin() function:

1
<div class="fb-login-button" data-max-rows="1" data-size="medium" data-show-faces="false" data-auto-logout-link="false" onlogin="javascript:CallAfterLogin();" scope="publish_actions,email"></div>

To check whether user is logged in or not in this tutorial, I’ve created session variable called $_SESSION[‘logged_in’], if you are using some user management system in your website, you have to make appropriate changes here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
session_start();
include_once("config.php");

if(!isset($_SESSION['logged_in']))
{
    echo '<div id="results">';
    echo '<!-- results will be placed here -->';
    echo '</div>';
    echo '<div id="LoginButton">';
    echo '<a href="#" rel="nofollow" class="fblogin-button" onClick="javascript:CallAfterLogin();return false;">Login with Facebook</a>';
    echo '</div>';

}
else
{
    echo 'Hi '. $_SESSION['user_name'].'! You are Logged in to facebook, <a href="?logout=1">Log Out</a>.';
}
?>

Here’s the Javascript code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
    FB.init({
        appId: '<?php echo $appId; ?>',
        cookie: true,xfbml: true,
        channelUrl: '<?php echo $return_url; ?>channel.php',
        oauth: true
        });
    };
(function() {
    var e = document.createElement('script');
    e.async = true;e.src = document.location.protocol +'//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);}());

function CallAfterLogin(){
    FB.login(function(response) {      
        if (response.status === "connected")
        {
            LodingAnimate(); //Animate login
            FB.api('/me', function(data) {
               
              if(data.email == null)
              {
                    //Facbeook user email is empty, you can check something like this.
                    alert("You must allow us to access your email id!");
                    ResetAnimate();

              }else{
                    AjaxResponse();
              }
             
          });
         }
    },
    {scope:'<?php echo $fbPermissions; ?>'});
}

//functions
function AjaxResponse()
{
     //Load data from the server and place the returned HTML into the matched element using jQuery Load().
     $( "#results" ).load( "process_facebook.php" );
}

//Show loading Image
function LodingAnimate()
{
    $("#LoginButton").hide(); //hide login button once user authorize the application
    $("#results").html('<img src="img/ajax-loader.gif" /> Please Wait Connecting...'); //show loading image while we process user
}

//Reset User button
function ResetAnimate()
{
    $("#LoginButton").show(); //Show login button
    $("#results").html(''); //reset element html
}

</script>

Process Requests

Once the Ajax request is made to process_facebook.php, it connects to Facebook and retrieves user details, and stores them in database table. Since we already have user session with JavaScript SDK, PHP-SDK should have no trouble using the Facebook session and APIs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
session_start();
include_once("config.php"); //Include configuration file.
require_once('inc/facebook.php' ); //include fb sdk

/* Detect HTTP_X_REQUESTED_WITH header sent by all recent browsers that support AJAX requests. */
if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
{      

    //initialize facebook sdk
    $facebook = new Facebook(array(
        'appId' => $appId,
        'secret' => $appSecret,
    ));
   
    $fbuser = $facebook->getUser();
   
    if ($fbuser) {
        try {
            // Proceed knowing you have a logged in user who's authenticated.
            $me = $facebook->api('/me'); //user
            $uid = $facebook->getUser();
        }
        catch (FacebookApiException $e)
        {
            //echo error_log($e);
            $fbuser = null;
        }
    }
   
    // redirect user to facebook login page if empty data or fresh login requires
    if (!$fbuser){
        $loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$return_url, false));
        header('Location: '.$loginUrl);
    }
   
    //user details
    $fullname = $me['first_name'].' '.$me['last_name'];
    $email = $me['email'];

    /* connect to mysql using mysqli */
   
    $mysqli = new mysqli($hostname, $db_username, $db_password,$db_name);
    if ($mysqli->connect_error) {
        die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
    }
   
    //Check user id in our database
    $UserCount = $mysqli->query("SELECT COUNT(id) as usercount FROM usertable WHERE fbid=$uid")->fetch_object()->usercount;
   
    if($UserCount)
    {  
        //User exist, Show welcome back message
        echo 'Ajax Response :<br /><strong>Welcome back '. $me['first_name'] . ' '. $me['last_name'].'!</strong> ( Facebook ID : '.$uid.') [<a href="'.$return_url.'?logout=1">Log Out</a>]';
       
        //print user facebook data
        echo '<pre>';
        print_r($me);
        echo '</pre>';

        //User is now connected, log him in
        login_user(true,$me['first_name'].' '.$me['last_name']);
    }
    else
    {
        //User is new, Show connected message and store info in our Database
        echo 'Ajax Response :<br />Hi '. $me['first_name'] . ' '. $me['last_name'].' ('.$uid.')! <br /> Now that you are logged in to Facebook using jQuery Ajax [<a href="'.$return_url.'?logout=1">Log Out</a>].
        <br />the information can be stored in database <br />'
;
        //print user facebook data
        echo '<pre>';
        print_r($me);
        echo '</pre>';
       
        // Insert user into Database.
        $mysqli->query("INSERT INTO usertable (fbid, fullname, email) VALUES ($uid, '$fullname','$email')");
               
    }
   
    $mysqli->close();
}

function login_user($loggedin,$user_name)
{
    /*
    function stores some session variables to imitate user login.
    We will use these session variables to keep user logged in, until s/he clicks log-out link.
    */

    $_SESSION['logged_in']=$loggedin;
    $_SESSION['user_name']=$user_name;
}
?>

That’s it! I am sure this will help you make your own Ajax Facebook Connect, Good luck.

Download Demo

  1. Your demo is not working.

     Reply
  2. e.async = true;e.src = document.location.protocol +’//connect.facebook.net/en_US/all.js’;
    document.getElementById(‘fb-root’).appendChild(e);}());

    Not working in IE 10 .. any help in this ?

     Reply
  3. hi I am install when login You must allow us to access your email id!
    how to fix please help thank you

     Reply
  4. Hi thanx for your help but my problem was due to my own setted anti virus for my browsers to stop the sucking redirections of pages.I have got stucked like that i have setted the anti virus on all browsers and when i was checking on other browsers it was giving the same error like “reference FB is not defined” and then by chance i removed the anti virus from the browser and it works properly

     Reply
  5. Hello to work properly I had to perform these alterations . I hope it helps.

    // line 58-71, index.php

    LodingAnimate(); //Animate login
    // Declare permission upstream js
    FB.api(‘/me’, {fields: ‘name, email’}, function(data) {

    if(data.email == null)
    {
    //Facbeook user email is empty, you can check something like this.
    alert(“You must allow us to access your email id!”);
    ResetAnimate();

    }else{
    AjaxResponse();
    }

    });

    // line 18-29, process_facebook.php

    if ($fbuser) {
    try {
    // Proceed knowing you have a logged in user who’s authenticated.

    // Declare permission upstream php
    $me = $facebook->api(‘/me?fields=id,first_name,last_name,email,gender,locale,picture’);

    $uid = $facebook->getUser();
    }
    catch (FacebookApiException $e)
    {
    //echo error_log($e);
    $fbuser = null;
    }
    }

     Reply
  6. Hi,I was working with your “ajax-facebook-connect-with-jquery” and it was working great as i want but now its giving an error that var FB is not defined so can u please help me to solve this error.Thanks

     Reply
  7. It is a great script thanx for this, but i m getting a problem when i try to login with faccebook after loading an error pops up that “You must allow us to access your email id!” can anyone help me to solve this plzzz

     Reply
  8. Hi…
    The example works fine, but the return is just id and name.
    Could You tell me what you still need to setup?

    Thanks a lot!

     Reply
  9. Is it possible to use this script on a http and have the authentication code on a https and then send the data back to the http. Why do this? So we don’t have to buy and ssl for each domain name as Facebook requires an ssl. Thanks

     Reply
  10. This article really helpful.If you guyz have some issue you can check this code that i have found.Thanks
    Login With Facebook Using PHP

     Reply
  11. thanks for the code, but i would like to ask, in ur code displays the account details, but when i get the result, details of my previous page (i.e signup page escpecially css) also gets displayed. i wish to display only result with additional information, how can i redirect the user to their profile page that contains info of

     Reply
  12. Great work, but for me it just keep on loading nothing is displayed.. keep on loading the ajax only please help

     Reply
  13. I have tried and it’s work. But when I login using my FB account in my website and so in your demo web, the result is different for my $uid number. And also I can’t get FB username by using $me[‘username’], just got an empty data.
    Is there something I did wrong or missing configuration??

     Reply
  14. How i can use in localhost… plz

     Reply
  15. hey thanks everything is working properly but i have one problem.. when i log in that page is just keeps on loading.. it was not showing any data like u have mentioned that Hi username and all those things are not coming.. instead it just keep on loading and loading..

     Reply
  16. Hi! I’ve tested your code and it works, so thank you :)

    I’ve been reading comments about getting the same fbid again and again, with this number: 2147483647. Turns out, that number is the largest INT value for MySQL. Change it to BIGINT so the script can store the fbid correctly.

     Reply
  17. Thank for good tutor. It’s work fine on my local host. But I lost the Sign in with facebook button when live. Any body can find the mistake of mine?

     Reply
  18. Thank you for the code
    just one thing – in config.php what url should I enter in $return_url. Please explain in detail as I didn’t got that from the explanation above.
    THANK YOU

     Reply
  19. Hello,
    can you make tutorial for php sdk 4 .. same as this – sign in with facebook

    thanks

     Reply
  20. how to get app id???

     Reply
  21. I receive this error “The application configuration does not allow the URL provided. One or more of the URLs provided are not permitted by the application configuration must match the URL of the web site or the URL of the home page. application, or the domain must be a subdomain of one of the application domains. “What is the solution ….?

     Reply
  22. why when i click refresh the session is lost?? cannot get it from ajax…

     Reply
  23. Hi, nice tutorial! will this work properly on mobile? or should I change or add something? ’cause I’m planning to use it on my web app. thanks! :) ^_^

     Reply
  24. This is working perfect on my site; thanks very much! Do you have details on how to replace the FB log in button with a custom one? You mention that you had done that, but after setting it all up, it looks like I’m using the default FB Login Button. CSS code does not seem to work on the IDs.

     Reply
  25. Thank u so very much.. Great work.. I just have single doubt please solve this thing..
    I am getting this error:
    Error
    App Not Setup: The developers of this app have not set up this app properly for Facebook Login.

    how can i resolve this. I have two accounts and provided app_id and app_secret from one account. when i try to login from other account this error is coming.

     Reply
    • hey my problem is solved.. thank you..
      but i have still one more problem.. when i log in that page is just keeps on loading.. it was not showing any data like u have mentioned that Hi username and all those things are not coming.. instead it just keep on loading and loading.. :(

  26. in login with facebook prperly work but after login could not return url my own website and can not create the session in my site only shown in page Loadding……. process Plz……help

     Reply
    • Same problem.. It seem that admin is no more here to reply to our quires.. Please provide us solution.
      ti just keep on loading nothing is displayed after that.. almost waited for more then few days for solution please provide any feasible solution.

  27. This is cool, and I used it in my application. But it is not working in IE 10. And your demo (http://www.saaraan.com/assets/ajax-facebook-connect/) is also not working in IE 10

     Reply
  28. Hi, First this is a helpful toturial

    everything works fine but my problem is i don’t get nothing into my database, what can i do for this, is there a solution, please i need some help.

     Reply
  29. how to get the birth date from your script

     Reply
  30. is there an easy way to add a redirect to this script?

     Reply
  31. There is a problem in the code:
    I want to make the connection button on some pages page.
    And it only works on INDEX. And any other page …

    You can make it work well in other pages (all pages on the site – for example)?
    Thank you

     Reply
  32. The code works, but he does not return the data from Facebook (name and email).
    What can you do?

    I have three files folder INC Facebook.
    According to my testing: AJAX code returns EROR (function AjaxResponse).
    What can you do?
    Thank you

     Reply
  33. Hi!
    First of all congratulations for the work and the page.

    I am trying to implement he piece of code into my site. Everything seems to work properly, when I try to login the process seems to be fine, but the program is not saving nothing into the database, and once the login is done, I am returned to the main page and just the login button is there, no message.

    Why can this happen?

    Regards!

     Reply
  34. I created a facebook app tutorial based on you and it worked perfectly, with only one problem, only the data of the first user who accessed the app that was fied auger in the mysql db, how can I solve this problem?

     Reply
  35. the download page doesnt work it displays encrypted code instead of saving the file to my hd… can you fix it please

     Reply
  36. Hi

    I connect to facebook via your script installed on my site and want to pass the user name details into a form.

    How to achieve this.

    Thanks

    Peter

     Reply
  37. i want after this step … post to user’s wall and post photos for user’s album

    how can i do that dear
    please reply

    we can use this data and we can make some edit in php ( post on wall page ) to make it post in users wall ( data mysql saved from this script )

    can we make integration

     Reply
  38. It really very good.. thanx a lot..

     Reply
  39. I really appreciate that these scripts are available. I have a question, though:

    Why is it that you are logging the user in the php script, if they were already logged in the jQuery part?

    I mean this instruction in the php:

    1
    login_user(true,$me['first_name'].' '.$me['last_name']);

    I believe the user has already been connected when this was executed in the browser:

    1
    CallAfterLogin();
     Reply
  40. This is great! I am really grateful that I found your post.

     Reply
  41. why mine only came out the connect with facebook button?others didn’t came out.

     Reply
  42. Can I reload the page after logging in ? My page hangs on the please wait while connecting

     Reply
  43. Howdy! Do you know if they make any plugins to
    assist with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m
    not seeing very good results. If you know of any please share.
    Thanks!

     Reply
  44. Your a Star.

    Thank you more than words can say…..

     Reply
  45. Hi very nice script. Is this normal that in localhost all my website is very slow…

     Reply
  46. It seems like :

    $result=mysql_query(“SELECT count(id) FROM usertable WHERE fbid=”.$uid);
    $num_rows=mysql_result($result,0);
    if ($num_rows>=1) {
    }

    else{

    }

    doesn’t work because in my database I have 4 same fbid… so it’s more than 1 but it go directly to “else” anyway…

     Reply
    • Try this :

      $result = mysql_query(“SELECT id FROM usertable WHERE fbid=”.$uid.” LIMIT 1″);
      $num_rows = mysql_num_rows($result);
      if ($num_rows>0) {
      // do stuff
      }else{
      // do other stuff
      }

  47. Hi I have one question, the script work very well but is that normal that when I Logout and Login in my database the script create a new user so in my database if i logout 5 times and login 5 times I will have 5 times my information in the database…

     Reply
  48. hi,

    i got this error when i try to login :

    Notice: Undefined variable: uid in /Applications/MAMP/htdocs/tarba-web/process_facebook.php on line 15

    Did you know what’s wrong with my config ?

     Reply
    • this errors seems to appear only in webkit browsers and on localhost environment.
      i use now FF for development and i didn’t get back this error.

  49. Hello, this great script it works very well, by cons I would change it so I can make it work with my site.
    How to replace this: login)) {?> Which is on my site??

     Reply
Message Type : Question Comment ?
  • Question : Can include code, jsFiddle, codePen etc using Markdown Syntax.
  • Comment : Short comments and questions.