Tuesday, December 9, 2014

Simple Login and Sign Up using Facebook Javascript SDK

Filling Sign Up and Login form were part of every web application nowadays. Users feel it hard to fill the sign up form again with same information. With Facebook API you can easily collect the basic user information needed for sign up.

This is the simplest working example for facebook based sign up.

This tutorial uses Facebook Javascript SDK v2.2

Demo|   Download

Needables

  • Facebook SDK
  • Facebook Application ID
You can create your application for free from here https://developers.facebook.com/apps


App ID (Application ID) can be obtained from the facebook application page, as show in above screenshot.

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
 <script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>

Signup Html Form

      <form class="form-signin" role="form">
            <div id="status"></div>
        <h2 class="form-signin-heading">User Registration</h2>
        
        <label for="inputFname" class="sr-only">First Name</label>
            <input type="text" id="inputFname" class="form-control" placeholder="First Name" required autofocus>
        
        <label for="inputLname" class="sr-only">First Name</label>
            <input type="text" id="inputLname" class="form-control" placeholder="Last Name" required >
            
        <label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required >
        
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
        <div class="checkbox">
          <label>
            <input type="checkbox" value="remember-me"> Remember me
          </label>
        </div>
        
        <button class="btn btn-sm btn-primary btn-block" type="submit">Sign Up</button> <button class="btn btn-sm btn-primary btn-block" onclick="_login();" type="submit">Sign Up using Facebook</button>
      </form>

Javascript

    <script>
  // Load the SDK asynchronously
  (function(thisdocument, scriptelement, id) {
    var js, fjs = thisdocument.getElementsByTagName(scriptelement)[0];
    if (thisdocument.getElementById(id)) return;
    
    js = thisdocument.createElement(scriptelement); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js"; //you can use 
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
    
  window.fbAsyncInit = function() {
  FB.init({
    appId      : '1449392918617564', //Your APP ID
    cookie     : true,  // enable cookies to allow the server to access 
                        // the session
    xfbml      : true,  // parse social plugins on this page
    version    : 'v2.1' // use version 2.1
  });

  // These three cases are handled in the callback function.
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });

  };
    
  // This is called with the results from from FB.getLoginStatus().
  function statusChangeCallback(response) {
    if (response.status === 'connected') {
      // Logged into your app and Facebook.
      _i();
    } else if (response.status === 'not_authorized') {
      // The person is logged into Facebook, but not your app.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this app.';
    }
  }  
  
  function _login() {
    FB.login(function(response) {
       // handle the response
       if(response.status==='connected') {
        _i();
       }
     }, {scope: 'public_profile,email'});
 }
 
 function _i(){
     FB.api('/me', function(response) {
        document.getElementById("inputFname").value = response.first_name;
        document.getElementById("inputLname").value = response.last_name;
        document.getElementById("inputEmail").value = response.email;
    });
 }

</script>

29 comments:

  1. Thanks for this nice piece of codes. it worked like a charm for me.

    ReplyDelete
  2. can u help me. its getting undefined value

    ReplyDelete
  3. yes it is showing undefined values in the text field.

    ReplyDelete
  4. ya its showing undefined vale can any one help please

    ReplyDelete
  5. Hi, It is a great script but it is giving an error "Uncaught ReferenceError: FB is not defined" when logging in via facebook login button can u please help??

    ReplyDelete
    Replies
    1. It is because the //connect.facebook.net/en_US/sdk.js change it to https://connect.facebook.net/en_US/sdk.js

      Delete
  6. Nimble Messaging Customer relationship management startup Nimble has raised $1 million in ... and Google to bring their contacts and messaging to Nimble.

    ReplyDelete
  7. Like most people i'm getting undefined value.Any idea why? (I see no console error)

    ReplyDelete
  8. If you changed the version in FB.init() to v2.5, try to modify FB.api() code as

    FB.api('/me', {fields: 'first_name,last_name,email'}, function(response) {
    ...

    ReplyDelete
    Replies
    1. Thanks! This helps to solve the undefined error!

      Delete
  9. how to store the user name and email to the database when i signup using facebook without taking the data to the text box ? I mean after facebook signup the user name and email will stored into the database and redirect to another page where i can give comment or anything... Please help me..

    ReplyDelete
    Replies
    1. See this Function

      function _i(){
      FB.api('/me', function(response) {
      document.getElementById("inputFname").value = response.first_name;
      document.getElementById("inputLname").value = response.last_name;
      document.getElementById("inputEmail").value = response.email;
      });
      }

      This is where the data is received from Facebook. You can do Ajax call and send back to server.

      Delete
  10. If any body gets the FB.init error. Usually it is because the facebook sdk javascript file is not loaded. You can check this through your browser network console.

    change the "//connect.facebook.net/en_US/sdk.js" to "https://connect.facebook.net/en_US/sdk.js"

    ReplyDelete
  11. If any body gets the FB.init error. Usually it is because the facebook sdk javascript file is not loaded. You can check this through your browser network console.

    change the "//connect.facebook.net/en_US/sdk.js" to "https://connect.facebook.net/en_US/sdk.js"

    ReplyDelete
  12. This is what I had been searching for, many thanks :)

    ReplyDelete
  13. This worked perfect for me

    thank-you, very helpful. :)

    ReplyDelete
  14. Link is dead !
    update the link pleae .

    ReplyDelete
    Replies
    1. Thank you for notifying.

      I am updating link URLs Now

      Delete
  15. Have you update the URL? it is not working still :(

    ReplyDelete
  16. Great tutorial its working. I just want city of user as well.
    How to get City of user? Could you please help me.

    ReplyDelete
  17. Hello Abdul,
    I'm able to fetch data into form. But I don't want it to be in that way I just want sign up facebook button and it should fetch data and it should be saved in my database.

    ReplyDelete
  18. Please help...In text box it shows undefined as a value..its urgent..

    ReplyDelete
  19. When i run the above Signup Html Form and javascript code together a error message {"error": "Please use POST request"} is displayed? Please help to understand

    ReplyDelete