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.
Related
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) {
I am trying to integrate facebook login logout in my website using facebook's PHP JS sdk. My problem is I cannot implement an independent login/logout option from actual facebook site. When I click the login button, it actually logs in the user's facebook and also my site. But, on clicking my site's logout button, It just logout from my site because I could only destroy my session. If I use autologoutlink="true" then it show the facebook logout button when logged in, but it does the logout of the actual facebook. I want to implement something like www.9gag.com.
I would really appreciate some help.
Here is my code, I am using CodeIgniter, and putting everything in the view/header.php .
?php
require 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'app_id',
'secret' => 'secret_key',
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
<fb:login-button scope="email" autologoutlink="true" ></fb:login-button>
JS
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
channelUrl : 'site_url',
cookie: true,
logging: true,
status: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
FB.api('/me', function(userInfo) {
//console.log(userInfo);
var options_ = {
'responsedata' : userInfo,
}
$.ajax({
type: 'POST',
url: 'user/facebooklogin',
data: options_,
dataType: "text",
success: function(msg){
console.log(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
}, {scope: 'email,user_likes'});
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
I'm working with jQuery Mobile.
My Code for move to details div ::
Go To Details
Now, I want to authenticate user with Facebook.
So I have applied ::
Login with Faceook
Function Calling for Authentication
function userLogin() {
FB.login(
function(response) {
if (response.authResponse) {
alert('logged in');
FB.api('/me', function(response) {
alert("Welcome " + response.name);
});
} else {
alert('not logged in');
}
},
{ scope: "email" }
);
}
I'm getting valid user response after authentication.Now I want to navigate to that details div.
So, how can I implement that ajax code after successfully login ??
Any suggestion will be appreciated.
Thanks.
Instead of changing the href attribute directly, you should bind the onclick event to a function returning true.
Modify your a tag.
Go To Details
Modify your userLogin function:
function userLogin() {
FB.login(
function(response) {
if (response.authResponse) {
alert('logged in');
FB.api('/me', function(response) {
alert("Welcome " + response.name);
});
} else {
alert('not logged in');
}
},
{ scope: "email" }
);
return true;
}
It seems that FB.login is an asynchronized operation. If you want to redirect after the login action, try to modify the location.hash after login. Note that the return value has changed to false.
function userLogin() {
var hash = '#details';
FB.login(
function(response) {
if (response.authResponse) {
alert('logged in');
FB.api('/me', function(response) {
alert("Welcome " + response.name);
window.location.hash = hash;
});
} else {
alert('not logged in');
}
},
{ scope: "email" }
);
return false;
}
Use $.ajax() for making a call to the Facebook API to authenticate and in the callback function of the ajax function, call the click event of the details link.
Maybe something like this,
$.ajax({
url : 'https://graph.facebook.com/me'+whatever,
success : function(){
$('#details').click()
}
});
The success function will be called when the ajax call is successful.
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
I would like to use fb.api to post on logged user, but just once. If I put this
var params = {};
params['message'] = 'gegeegeggegall! Check out www.facebook.com/trashcandyrock for more info.';
params['name'] = 'gegeggeeg - gegegege';
params['description'] = 'Check out Tegegegeg! Win merch by playing and reccomending to your friends.';
params['link'] = 'http://www.bblblba.com';
params['picture'] = 'http://summer-mourning.zoocha.com/uploads/thumb.png';
params['caption'] = 'Tgegegegeeg';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Published to stream - you might want to delete it now!');
}
});
It posts to users wall everytime he refreshes the site?
What to do?
What is triggering the FB.api call? If it's just code within a tag then it's going to run as soon as the browser gets to that point.
You could possibly store some sort of cookie value or something after the FB.api call then check it on page load, but that seems like more work than is probably needed.
Do you want him to post it only once, ever?
If so, you're going to need to create a "state". In order to do this, you could do it client sided (with cookies), or server sided (with a database).
Create a boolean variable named "posted", and store it in a cookie or in a database (since you're using javascript, it's probably easier to use a cookie).
var posted=getCookie("posted");
if(!posted)
{
//call the FB.api();
setCookie("posted", true, duration);
}
Definition of setCookie and getCookie: http://www.w3schools.com/JS/js_cookies.asp
You could run a FQL query and check to see if the message has already been posted by querying the stream table with your app id. Something like:
<!DOCTYPE html>
<html>
<body>
<div id="fb-root"></div>
Post To Wall
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({ appId : '**yourAppID**', status : true, cookie : true, xfbml : true });
function postToWall() {
FB.login(function(response) {
if (response.session) {
FB.api(
{
method: 'fql.query',
query: 'SELECT post_id, message from stream where app_id = **yourAppID** and source_id = me()'
},
function(response) {
if(response.length == 0){
FB.ui(
{
method: 'feed',
name: 'Facebook Dialogs',
link: 'https://developers.facebook.com/docs/reference/dialogs/',
picture: 'http://fbrell.com/f8.jpg',
caption: 'Reference Documentation',
description: 'Dialogs provide a simple, consistent interface for applications to interface with users.',
message: 'Facebook Dialogs are easy!'
},
function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
}
else {
alert('User already posted this message');
}
}
);
}
} , {perms:''});
}
</script>
</body>
</html>