FB.api name undefined - javascript

I'm working on a new Facebook App for my website using Facebook Connect. I'm using the JS SDK and I try to display the name of the user. Here is my code :
window.fbAsyncInit = function() {
FB.init({
appId : 'myappid', // App ID
oauth : 'true',
channelUrl : '//mychannelfile', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.login', function (response) {
// do something with response
});
var connecter=false;
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
connecter=true;
FB.api('/me', function(user) {
console.log(user.name);
});
}
else connecter=false;
});
};
If I check the console the result of user.name is undefined when the user is connected. I don't understand what I'm doing wrong.
Thank you for your help !

window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '176854392480453',
status : true,
xfbml : true
});
// Additional initialization code such as adding Event Listeners goes here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
alert("connected");
connecter=true;
FB.api('/me', function(user) {
alert(user.name);
alert(user.first_name);
alert(user.last_name);
alert(user.email);
});
}
});

Related

Facebook login callback returns name but not email address

I'm using Facebook login in the simplest way, and getting a call back response:
<div id="fb-root"></div>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v6.0&appId=881911462250499&autoLogAppEvents=1"></script>
<script>
window.fbAsyncInit = function() {
FB.getLoginStatus(function(response) {
FB.api('/me', function (response) {
console.log(response);
});
});
}
</script>
I log the response to the console and receive the name and id, but not email address. How can I get the email as well? Upon researching it, it should get it by default, am I wrong?
According to the Fb docs, This is how you do it.
function statusChangeCallback(response) { // Called with the results from FB.getLoginStatus().
console.log('statusChangeCallback');
console.log(response); // The current login status of the person.
if (response.status === 'connected') { // Logged into your webpage and Facebook.
testAPI();
} else { // Not logged into your webpage or we are unable to tell.
document.getElementById('status').innerHTML = 'Please log ' +
'into this webpage.';
}
}
window.fbAsyncInit = function() {
FB.init({
appId : '{app-id}',
cookie : true, // Enable cookies to allow the server to access the session.
xfbml : true, // Parse social plugins on this webpage.
version : '{api-version}' // Use this Graph API version for this call.
});
FB.getLoginStatus(function(response) { // Called after the JS SDK has been initialized.
statusChangeCallback(response); // Returns the login status.
});
};
function testAPI() { // Testing Graph API after login. See statusChangeCallback() for when this call is made.
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
});
}
You can check login status in this way.
function checkLoginState() { // Called when a person is finished with the Login Button.
FB.getLoginStatus(function(response) { // See the onlogin handler
statusChangeCallback(response);
});
}
By default, fb allows only basic permissions. What you require is additional permission, hence you have to request it this way.
FB.login(function(response) {
// handle the response
}, {scope: 'email,user_likes'});
You can read more about it here. Hope it helps :)
Ok got it, I was confused and it shoudl be here:
FB.api('/me', { locale: 'tr_TR', fields: 'email,name' }, function (response) {

Email not able to retrieve from facebook javascript SDK [duplicate]

I am using JavaScript API to create my app for Facebook. The problem is, it's returning
email = undefined.
I don't know why? And if I use Facebook login/logout button on my app then the alert shows correct email id of the user but I don't want to do that.
What am I missing?
Here is my code:
<p><fb:login-button autologoutlink="true" perms="user_about_me,email"></fb:login-button></p>
<script>
window.fbAsyncInit = function () {
FB.init({ appId: '250180631699888', status: true, cookie: true,
xfbml: true
});
FB.getLoginStatus(function (response) {
if (response.session) {
greet();
}
});
};
(function () {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
} ());
function greet() {
FB.api('/me', function (response) {
alert('Welcome, ' + response.name + "!");
alert('Your email id is : '+ response.email);
});
}
</script>
// https://developers.facebook.com/docs/javascript/reference/FB.api/
// v2.4
FB.api('/me', { locale: 'en_US', fields: 'name, email' },
function(response) {
console.log(response.email);
}
);
here is example how i retrieve user name and e-mail:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
$(function() {
FB.init({
appId : 'APP_ID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
getCurrentUserInfo(response)
} else {
FB.login(function(response) {
if (response.authResponse){
getCurrentUserInfo(response)
} else {
console.log('Auth cancelled.')
}
}, { scope: 'email' });
}
});
function getCurrentUserInfo() {
FB.api('/me', function(userInfo) {
console.log(userInfo.name + ': ' + userInfo.email);
});
}
});
</script>
According to the latest info on the facebook page you should use 'scope' instead of perms.
https://developers.facebook.com/docs/reference/javascript/FB.login/
If you visit
https://developers.facebook.com/tools/console/
and use the fb-api -> user-info example as a starting point, then logout and back in again, it should ask you for email perms and you can see your email being printed. It is done using response.email as you mention in your post.
<button id="fb-login">Login & Permissions</button>
<script>
document.getElementById('fb-login').onclick = function() {
var cb = function(response) {
Log.info('FB.login callback', response);
if (response.status === 'connected') {
Log.info('User logged in');
} else {
Log.info('User is logged out');
}
};
FB.login(cb, { scope: 'email' });
};
</script>
Use this to for extra permission
for more details visit :
https://www.fbrell.com/examples/
In this code i have get user data form facebook and store into my database using ajax
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me?fields=email,name,first_name,last_name', function(response)
{
FB.api(
"/"+response.id+"/picture?height=100",
function (responses) {
//console.log(responses.data.url)
response['profile_pic']=responses.data.url;
$.ajax({
type:"POST",
url:'<?php echo base_url(); ?>'+'home/facebook_get_signup',
data:response,
success:function(res)
{
if(res=='success')
{
window.location='<?php echo base_url(); ?>';
}
if(res=='exists')
{
window.location='<?php echo base_url(); ?>';
}
}
});
}
)
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
// handle the response
}, {scope: 'email,user_likes'});
There are a couple of things wrong with your solution. First of all you are using the old authentication scheme. You should use the new one described here :
https://developers.facebook.com/docs/reference/javascript/
You need to add the oauth:true to your init function, and make sure that your getLoginStatus looks for the new type of response.
When that is said you need to make sure you have the right permissions to see the users e-mail. You can see the required permissions here:
http://developers.facebook.com/docs/reference/api/user/
You get those by using the FB.login function as described by TommyBs in another answer.
Once you have those options you can use the FB.api function to get the e-mail.

FacebookConnect redirect no longer works

I have been successfully doing a redirect after FacebookConnect for a while, but it has now stopped working. The only thing I can think I may have changed is updating my Facebook references using NuGet. Here is my code, can anybody tell me why it no longer works?
<script type="text/javascript">
$(document).ready(function () {
window.FB.init({ appId: 'xxxx', status: true, cookie: true, xfbml: true });
$('#fbLogin').click(function () {
FB.Event.subscribe('auth.statusChange', function (response) {
alert('The status of the session is: ' + response.status);
if (response.status == 'connected') {
window.location.href = '#Account.Urls.FacebookConnect()';
}
}, { perms: 'email' });
});
});
</script>
<fb:login-button autologoutlink="false" perms="email" id="fbLogin">
</fb:login-button>
Whether I put an alert for response.status == 'connected' or not, neither alert is reached
Got it working with a mixture of CBroe's suggestion and using auth.authResponseChange instead of auth.statusChange

Facebook Login Button callback function

I got a Problem with the Facebook Login on my Website. The Code Below is my FB-Connect Code. The commented part of the code sign's me in to my Website. My Problem is when i "reactivate" this code it logs me in instandly everytime i visit the page. But i want to log the user in when he clicks the "Login with Facebook"-Button. When I clicks the facebook login button a Popup shows up and nothing happens..
Can i somehow call a JS function when i click the FB-Connect button?
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxxxxxx', // App ID
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
var login = false;
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
console.log('connected');
login=true;
var uid = response.authResponse.userID;
//this part of the code below redircts me to the part, where i login to my system.
/*var accessToken = response.authResponse.accessToken;
$.ajax({
type: 'POST',
url: '/?eID=login',
data: $(this).serialize(),
success: function(msg) {
alert("LOGIN");
$('#content').load('/live-session/tickets/');
}
});*/
}});
You need to use FB.login function on click on fb connect button and don't use FB.getLoginStatus
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
From Doc
FB.getLoginStatus allows you to determine if a user is logged in to
Facebook and has authenticated your app.
So, if you don't want to check whether user has logged in on page load, don't call this
When I clicks the facebook login button a Popup shows up and nothing happens..
If you had already authorized the app and authenticated, facebook wont ask you again for login and authorization

Javascript FB.api - undefined error

I am trying to use JS interface for facebook api and it is my first application for it.
Here is a snippet:
HTML:
<div id="fb-root"></div>
<script src="https://connect.facebook.net/ru_RU/all.js"></script>
<script type="text/javascript">facebook_init();</script>
JS:
function facebook_init() {
FB.init({
appId : '<MY APP ID IS HERE>',
channelUrl : '/media/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.api('/me', function(response) {
alert('Your name is ' + response.name);
});
}
channel.html:
<script src="https://connect.facebook.net/ru_RU/all.js"></script>
I have 'Your name is undefined' when I load this page.
But this code
FB.ui({ method: 'apprequests',
message: 'MSG',
title: 'TITLE'});
works as expected.
Could you please help me?
Thanks!
If you log your response variable via console.log(response) you'll see what's wrong:
You'll get an error object with this message:
"An active access token must be used to query information about the current user."
So if you want to get information about the current user you have to send also an Access Token. To get more information about this check the Facebook JS SDK page.
You need to make sure that the user has logged into Facebook and authorized your app, before you call FB.api('/me', ...).
Here's the general information: http://developers.facebook.com/docs/guides/web/#login
To overcome with Undefined problem use the following code:
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '<APP ID>',
status : true,
xfbml : true
});
// Additional initialization code such as adding Event Listeners goes here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
alert("connected");
connecter=true;
FB.api('/me', function(user) {
alert(user.name);
alert(user.first_name);
alert(user.last_name);
alert(user.email);
});
}
});

Categories

Resources