1

I'm trying to get Facebook login to work on my website. I have the following Javascript/AJAX code:

var antwoord="";
var message="";

function myFacebookLogin() {
    FB.login(function() { 
    FB.api('/me','GET',{"fields":"id,email,birthday,gender,first_name,last_name"}, function(response) {
        antwoord = response;
    })
}, {scope:'email,user_birthday'});

$.ajax({
    url:  '/dev/php/registerfb.php',
    type: 'POST',
    data: {firstname:antwoord.first_name,lastname:antwoord.last_name,email:antwoord.email,gender:antwoord.gender,date:antwoord.birthdate,id:antwoord.id},
    success: function(response) {
        console.log(response);
    },
    error: function(error) {
        console.log(error);
    }
})
}

The problem seems to be that Facebook gives a response before the user has logged in. That way the AJAX code gets triggered while there isn't even any response. I probably made a silly mistake somewhere.

Kevin Tinnemans
  • 709
  • 11
  • 33

1 Answers1

1

Yes, that's right the ajax is called before the login response is received
one way to solve this is to wrap the ajax call in a function
then call the function after the response is received

var antwoord="";
var message="";

function myFacebookLogin() {
    FB.login(function() { 
        FB.api('/me', 'GET', {"fields":"id,email,birthday,gender,first_name,last_name"},
        function(response) {
            antwoord = response;
            callTheAjax();
        })
    }, {scope:'email,user_birthday'});

    function callTheAjax() {
        $.ajax({
            url:  '/dev/php/registerfb.php',
            type: 'POST',
            data: {firstname:antwoord.first_name,lastname:antwoord.last_name,email:antwoord.email,gender:antwoord.gender,date:antwoord.birthdate,id:antwoord.id},
            success: function(response) {
                console.log(response);
            },
            error: function(error) {
                console.log(error);
            }
        });
    }
}