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>

38 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
    2. Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.


      I've tried this code, this error appears.

      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
  20. It was showing this error msg..plz help me out

    Can't load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings.

    ReplyDelete
  21. I am glad after reading that post. I was searching that topic from few days its increase my knowledge.
    Home Improvement Write for us

    ReplyDelete
  22. The dropshipping business is heavily dependent upon reliable suppliers. This is another problem, you are at the mercy of your supplier. This is why you also need to know how to create original product images. This is only some ad images and ad copy, not all of them. And it turns out it is only a very brief description for products in the beginning. These products are “Done FOR You” with the images and ad copy installed.
    When you post in the talk forum, you might wait a day or two for someone to get back to you. When I first joined the course, Steve and Aidan were inside periodically to answer questions. They promptly deleted messages they thought were too negative or just complainers. Then, it didn’t take long after the refund expired and they just disappeared.
    Step 3: Pick Your Profit Path
    The ones I tried were either outdated, recycled methods that no longer work, or courses for people that are willing to invest a $100k+ right off the bat. You can either use the Fast Track System or the Expand your Inventory option to load and sell your products on the platform. With a 30-day money-back guarantee, you can choose to get your money back if you feel that the Kibo Eclipse program is not the one for you, or if it is too difficult for you to understand .
    It’s an instant free traffic source, mentors shares very cheap paid traffic resources too. These free and paid traffic resources are untapped and underrated. Let me reveal the traffic source on the member’s area overview section.
    Kibo Eclipse Review - https://www.reviewengin.com/kibo-eclipse-review/

    ReplyDelete
  23. It allows brands to locate and advertise directly to their target audience. Consumers are becoming increasingly skeptical of brands and their marketing tactics, and building trust is crucial. Advertising through influencers allows brands to promote through someone that a niche community watches, engages with and trusts on a daily basis. So, instead of being skeptical of a commercial or social media ad, consumers are trusting that if their influencer of choice loves the product, they will too. Influencers operate independently, creating their own content and integrating a company’s advertising specifications into it. The influencer is in control of the brand's message, choosing how they would like to portray it.
    Instead of filming short commercials about adventurers, the company found real adventurers, gave them a GoPro, and told them to upload their good times. Naturally, these influencers shared this with their networks, who envisioned themselves recording their own adventures with the same device. Getting people on social media to stop, look at your post, like it, leave a comment, and – miracle of all miracles – share it is hard. It may go without saying, but you can’t just partner with any influencer. https://www.reviewengin.com/5-reasons-you-should-take-advantage-of-influencer-marketing/

    ReplyDelete
  24. You must also have a place from which to sell your products. Place can sometimes be very ephemeral -- for example a phone number might be the place. For most physical products we tend to think of the place as a store or shop of some sort. But if you think about it a bit more you realize that the place for any traditional mail order company is the combination of an ad or a catalog and a phone number or a mail box. Producers - these are the people who create the products and services that sellers offer to buyers.
    The payment gateway is the tool that transmits the online payment data to the processor so that the transaction may continue. It’s what authorizes payments for “card-not-present” situations like ecommerce. It’s basically the online equivalent of the physical equipment you’d use to take credit cards in person. I don’t think you can start any business without some capital. You can bootstrap the content marketing side by creating content yourself. But you will need at least some money for hosting and software. https://www.reviewengin.com/ecommerce-business-ideas/

    ReplyDelete
  25. You will know without a doubt which trades you should take and which ones you should not. To say that Russ Horn’s systems are all the same would not be fair. They do have many elements in common as we just explored. Yet they also have some important differences. This is primarily in the form of who they are designed for and marketed to with each successive system.
    RUSS HORN NEW TRADING SYSTEM TRADEONIX REVIEW
    An easy to follow visual that you can use to very quickly know what you should do with every setup. As I get older, I want to spend as little time as I need to in front of my computer. I now can spend as little as 15 minutes in front of my charts and be done trading for the day. Other times, I might have to watch them for 90 minutes either way I'm not spending a whole day in front of my computer, a few hours tops and I'm done for the day.
    Remember, every big loss starts out as a small loss. What looks like a perfect setup in this trading session will just drain your account. Why sometimes no trade is the best trade you can make. This last DVD is certainly not the least. I dedicate hours of teaching and training to reinforce everything you have learned throughout the course. https://www.reviewengin.com/rapid-results-method-review/

    ReplyDelete
Previous Post Next Post