I am using Facebook Javascript SDK with a custom login button:
<button id="login" onclick="javascript:login();">Login Facebook</button>
and javascript function is:
function login() {
FB.login(function(response) {
// handle the response
FB.api('/me', { locale: 'en_US', fields: 'name, email' },
function(response) {
email = response.email;
name = response.name;
}
);
FB.getLoginStatus(function(response) {
user_id = response.authResponse.userID;
if (response.status === 'connected') {
console.log('Response goes here! ' + email + ' of ' + name + ' of ' + user_id);
$.ajax({
url: "includes/ajax_fb.php",
data:{email:email,name:name,user_id:user_id},
type: "POST",
success:function (data) {
if(!data.error) {
// location.reload(true);
$("#ajax-response").html(data);
}
}
});
} else if (response.status === 'not_authorized') {
alert(response.status);
} else {
alert(response.status);
}
});
}, {scope: 'public_profile,email'});
}
When I press login button once I am connected but no console.log and no data in #ajax-response are shown.
When I press login button for second time, console.log and data in #ajax-response are shown in console.
After the second button press, console.log and data in #ajax-response are shown with each consecutive button press.
I was pointed to How do I return the response from an asynchronous call? for a solution, and after thoroughly examining it, I understand I need to restructure my code to "Let functions accept callbacks". I've been trying to get it to work for hours now, and still cant figure it out :(
How do I restructure my code to make console.log and data in #ajax-response to show on the very first button press?