Kevin Tinnemans Kevin Tinnemans -4 years ago 91
Ajax Question

Facebook gives response before user can log in

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.

Answer Source

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);
            }
        });
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download