facebook login script stopped working - javascript

I dont know what happened to my script, it was working great, then it suddenly doesnt return email (returns undefined), but the firstname, lastname and username work fine.
here is the code
<script type="text/javascript">
// initialize the library with the API key
FB.init({ appId: 'XXXXXXXXXX',status: true, cookie: true, xfbml: true, oauth: true });
function login() {
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 + '.email :' + response.email);
console.log('Good to see you, ' + ",gender:" + response.gender + "another : " + response.first_name);
console.log('Good to see you, ' + response.username + '.last_name :' + response.last_name);
// console.log('Good to see you, ' + response);
}, { scope: 'email' });
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
</script>
I havent changed anything though, what could be wrong ?

To get the email, { scope: 'email' } needs to be be passed to FB.login, not as a parameter to FB.api.
FB.login(function (response) {
...
}, { scope: 'email' });

Related

i can't pass javascript variable to servlet without submitting a form

function gameLogin() {
var usernameToPass;
console.log('Fetching information from facebool.... ');
FB.api('/me', function (response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.name + '!';
//pass user name to Servlet
usernameToPass = response.name;
pass(usernameToPass);
});
}
function pass(name) {
$.ajax({
url: 'GameManagerServlet',
data: {
username: name
},
type: 'GET',
success: function (name) {
console.log(name);
}
});
}
so basically i have this script in my jsp using Facebook login api got username then stored in a variable, and trying to pass to my servlet by another function, because my servlet needs to receive the username when the page is loaded, i've tried some ways like by ajax, but the server side when i use request.getParameter("username"); but always got null. Could you help me to fix this problem? Thanks a lot!
You should use callback function like below.
var usernameToPass;
function gameLogin() {
console.log('Fetching information from facebool.... ');
FB.api('/me', function (response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.name + '!';
//pass user name to Servlet
usernameToPass = response.name;
pass(callback){
callback(usernameToPass);
};
}
function pass(function(name) {
$.ajax({
url: 'GameManagerServlet',
data: {
username: name
},
type: 'GET',
success: function (successname) {
console.log(successname);
}
});
})

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.

Facebook JS SDK check specific like of logged in user

I can't seem to check if a logged in user likes a specific Facebook Business page(URL). This keeps coming back as undefined. Notice anything wrong here?
function postLike() {
FB.api(
'https://graph.facebook.com/me/og.likes',
'get',
{ id: objectToLike,
privacy: {'value': 'SELF'} },
function(response) {
if (!response) {
alert('Error occurred.');
} else if (response.error) {
document.getElementById('result').innerHTML =
'Error: ' + response.error.message;
} else {
document.getElementById('result').innerHTML =
'Business page is ' +
response.object + '</a>';
}
}
);
}

How to post to Facebook fanpage as fanpage, not user

How can I post on fanpage wall as fanpage not as a user - using javascript sdk.
RIght now on Init im receiving menage_pages and acquiring suitable fanpage id, how can i change call below?
var target = '/'+params.target+'/feed'
FB.api(target,
'post',
{ message: params.message,
link: params.link,
picture: params.picture,
caption: params.caption,
description: params.description,
name: params.name
}
,function(response) {
if (!response || response.error) {
$("#error").removeClass('hidden');
} else {
$("#success").removeClass('hidden');
}
});
You need the following permissions:
publish_stream
manage_pages
Now we call the page object to retrieve the page's access_token and then post with that token, something like:
function postToPage() {
var page_id = 'MY_PAGE_ID';
FB.api('/' + page_id, {fields: 'access_token'}, function(resp) {
if(resp.access_token) {
FB.api('/' + page_id + '/feed',
'post',
{ message: "I'm a Page!", access_token: resp.access_token }
,function(response) {
console.log(response);
});
}
});
}
Result:
More about this in my tutorial.
All you need is those three functionalities to be implemented:
First one is for setting the basic parameters for your Application(XXX-APP needs to be changed with your real id of application).
Second, function fol login to Facebook and granting needed permissions to be able to post to Facebook.
Third function is for posting to Facebook(XXX-page need to be changed with ID of the Page that you want to post something)
FB.init({ appId: 'XXX-APP', status: true, cookie: true, xfbml: true, oauth: true });
access_token = '';
function loginFB(){
FB.login(function(response) {
if (response.authResponse) {
access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'publish_stream,manage_pages'});
}
function postToPage() {
FB.api('/XXX-page', {fields: 'access_token'}, function(resp) {
if(resp.access_token) {
FB.api('/' + page_id + '/feed',
'post',
{ message: "MSG", access_token: resp.access_token }
,function(response) {
console.log(response);
});
}
});
}

json.stringify is not a function error at JavaScript

I'm using login, registration Facebook API with JavaScript in a WordPress plugin. I got this error
json.stringify is not a function error at JavaScript.
What is the issue? I use this code:
<div id="fb-root"></div>
<script type="text/javascript">
var button;
var userInfo;
window.fbAsyncInit = function() {
FB.init({ appId: '154333274632806',
status: true,
cookie: true,
xfbml: true,
oauth: true});
showLoader(true);
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
if (response.authResponse) {
//user is already logged in and connected
FB.api('/me', function(info) {
login(response, info);
});
button.onclick = function() {
FB.logout(function(response) {
logout(response);
});
};
}
else {
//user is not connected to your app or logged out
button.innerHTML = 'Login';
button.onclick = function() {
showLoader(true);
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
}, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
}
}
}
// Run once with current status and whenever the status changes.
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(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);
}());
function login(response, info){
if (response.authResponse) {
var accessToken = response.authResponse.accessToken;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name
+ "<br /> Your Access Token: " + accessToken;
button.innerHTML = 'Logout';
showLoader(false);
document.getElementById('other').style.display = "block";
}
}
function logout(response){
userInfo.innerHTML = "";
document.getElementById('debug').innerHTML = "";
document.getElementById('other').style.display = "none";
showLoader(false);
}
//stream publish method
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
showLoader(true);
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: name,
caption: '',
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {
showLoader(false);
});
}
function showStream(){
FB.api('/me', function(response) {
//console.log(response.id);
streamPublish(response.name, 'I like the articles of Thinkdiff.net', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
});
}
function share(){
showLoader(true);
var share = {
method: 'stream.share',
u: 'http://thinkdiff.net/'
};
FB.ui(share, function(response) {
showLoader(false);
console.log(response);
});
}
function graphStreamPublish(){
showLoader(true);
FB.api('/me/feed', 'post',
{
message : "I love thinkdiff.net for facebook app development tutorials",
link : 'http://ithinkdiff.net',
picture : 'http://thinkdiff.net/iphone/lucky7_ios.jpg',
name : 'iOS Apps & Games',
description : 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'
},
function(response) {
showLoader(false);
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
function fqlQuery(){
showLoader(true);
FB.api('/me', function(response) {
showLoader(false);
//http://developers.facebook.com/docs/reference/fql/user/
var query = FB.Data.query('select name, profile_url, sex, pic_small from user where uid={0}', response.id);
query.wait(function(rows) {
document.getElementById('debug').innerHTML =
'FQL Information: '+ "<br />" +
'Your name: ' + rows[0].name + "<br />" +
'Your Sex: ' + (rows[0].sex!= undefined ? rows[0].sex : "") + "<br />" +
'Your Profile: ' + "<a href='" + rows[0].profile_url + "'>" + rows[0].profile_url + "</a>" + "<br />" +
'<img src="' + rows[0].pic_small + '" alt="" />' + "<br />";
});
});
}
function setStatus(){
showLoader(true);
status1 = document.getElementById('status').value;
FB.api(
{
method: 'status.set',
status: status1
},
function(response) {
if (response == 0){
alert('Your facebook status not updated. Give Status Update Permission.');
}
else{
alert('Your facebook status updated');
}
showLoader(false);
}
);
}
function showLoader(status){
if (status)
document.getElementById('loader').style.display = 'block';
else
document.getElementById('loader').style.display = 'none';
}
</script>
<h3>New JavaScript SDK & OAuth 2.0 based FBConnect Tutorial | Thinkdiff.net</h3>
<button id="fb-auth">Login</button>
<div id="loader" style="display:none">
<img src="ajax-loader.gif" alt="loading" />
</div>
<br />
<div id="user-info"></div>
<br />
<div id="debug"></div>
<div id="other" style="display:none">
Publish Wall Post |
Share With Your Friends |
Publish Stream Using Graph API |
FQL Query Example
<br />
<textarea id="status" cols="50" rows="5">Write your status here and click 'Status Set Using Legacy Api Call'</textarea>
<br />
Status Set Using Legacy Api Call
</div>
You can find a link to the code for json.stringify here -
http://www.json.org/js.html
If you add that to your code then the error should go away.
Alternatively, you could add a reference to this script to your code -
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
What browser are you using? Not every browser supports native JSON parsing like you are trying. Also, it should be:
JSON.stringify

Categories

Resources