Fb.api undefined user - javascript

I have the following problem:
Once the user is logged in facebook if I run the following code:
FB.api('/me', function(user) {
alert(user.name);
});
It pops up an alert with "Udefined" written.
But if I change the code in the following way:
FB.api( /[MY_REAL_FACEBOOK_ID], function(user) {
alert(user.name);
});
It response in the correct manner.
How it is possible ?
Why '/me' never works ?

I think you might be querying "/me" in context of the app rather than the user. The documentation is not as explicit as it could be, but I've had the same issue.
Are you able to use FB.getLoginStatus?
After I have FB.init set up, I make a call to FB.getLoginStatus similar to what is found below. There might be a better way on how to do this, but it works for me.
Hopefully this helps:
FB.getLoginStatus(function (response) {
if (response.session) {
// logged in and connected user, someone you know
graphUrl = "https://graph.facebook.com/me?access_token=" + response.session.access_token + "&callback=displayUser"
var script = document.createElement("script");
script.src = graphUrl;
document.body.appendChild(script);
} else {
// no user session available, someone you dont know
}});
function displayUser(user) {
alert(user.name);
}

Use the below code to overcome the Undefined problem:
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : your_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);
});
}
});

Related

Facebook Javascript API keeps reconnecting [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm building a site which, when the user connects to Facebook, appends a profile picture to a div, amongst other things. When I leave the site open for a while and come back, I see that the same profile picture has been appended multiple times, so clearly the Facebook connection closes and reopens every so often.
Is there any way to stop this?
Thanks
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '219892158204692',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
fbconnect = true;
$('#fbloginbutton').hide();
$('#friendcontainer').append('<span id="loader"><center>Loading...</center></span>');
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
FB.api(
"/me",
function (response) {
if (response && !response.error) {
fbid = response['id'];
user['id'] = response['id'];
getuserhighscore(user['id']);
userpercentile(parseInt(user['highscore']));
$('#statscontainer').append('<span class="label">Highest Score</span>: '+user['highscore']+'<br>');
$('#statscontainer').append('<span class="label">Percentile (global)</span>: '+user['percentile']+'<br>');
drawuserchart(user['id']);
}
}
);
FB.api(
"/fql?q=select%20uid%2C%20first_name%2C%20is_app_user%20from%20user%20where%20uid%20in%20(select%20uid2%20from%20friend%20where%20uid1%3Dme())%20and%20is_app_user%3D1",
function (response) {
console.log('friends installed:');
console.log(response);
console.log(response['data'][0].id);
var responseArray = [];
responseArray.push(response);
console.log(responseArray);
user['friends'] = response['data'].length;
if (response && !response.error) {
for (var i=0;i<response['data'].length;i++){
friend = response['data'][i];
console.log('friend coming up');
console.log(friend);
friends.push(friend.uid);
$('#friendcontainer').append('<div class="friendbox" id="'+friend.uid+'"></div>');
$('#'+friend.uid+'').append('<img class="friendpic" src="https://graph.facebook.com/'+friend.uid+'/picture?height=60&width=60&type=square">');
$('#'+friend.uid+'').append('<div class="friendname">'+friend.first_name+'</div>');
gethighscore(friend.uid);
$('#'+friend.uid+'').append(' - '+friendscores[i]+'');
console.log(friendscores);
}
$('#loader').remove();
user['friendrank'] = 1;
for (var i=0;i<friendscores.length;i++){
if(friendscores[i] > user['highscore']){
user['friendrank']++;
}
}
$('#statscontainer').append('<span class="label">Rank (among friends)</span>: '+user['friendrank']+'<br>');
} else {
console.log(response.error)
}
}
);
console.log(friends);
console.log(user)
FB.api(
"/me/picture",
{
"redirect": false,
"height": "100",
"type": "normal",
"width": "100"
},
function (response) {
if (response && !response.error) {
user['picture'] = response['data']['url'];
console.log(user['picture']);
$('#thumbnail').append('<img id="thumbnailpic" src="'+user['picture']+'">');
}
}
);
testAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
FB.login();
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login();
}
});
};
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
$('#sidebar').slideDown("slow");
});
}
</script>
FB.Event.subscribe on auth.authResponseChange is triggered whenever there's change in the auth. A user session is maintained for some minutes, so what's happening is the event is triggered after sometime and the photos are appended again.
You should not write this whole code in this event block.
So, if you want to do this all in this same page, what you can do is, maintain a bool, say bool isLoaded=false;, now when your call is completed: isLoaded=true; indicating that the data is loaded.
And make your API calls whenever it is false, just like this-
if (response.status === 'connected') {
if(isLoaded){
fbconnect = true;
....
....
}
else
// dont do anything
}
Hope that helps!

too much recursion - jquery - why?

I am struggling with this issue for a couple of hours, but no sign of success. I am trying to implement the facebook login. this is my code:
function fblogin() {
FB.login(function(response) {
if (response.authResponse) {
var url = '/me?fields=name,email';
FB.api(url, function(response) {
$('#email_login').val(response.email);
$('#pwd_login').val(response.name);
$('#sess_id').val(response.id);
if($('#evil_username').val()==""){
$('#loginform').submit();
}else{
// doh you are bot
}
});
} else {
// cancelled
}
}, {scope:'email'});
}
but once i click facebook login button, i am getting too much recursion in console. why is that? i read lots of problems here in stackoverflow regarding this issue, but couldnot find the clue for my case.
i dont have recursion here, but what is happening which causes that recursion?
and there is a call for it from
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxx',
channelUrl : '//www.mydomain.de/channel.html',
status : true,
cookie : true,
xfbml : true
});
// Additional init code here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// connected
} else if (response.status === 'not_authorized') {
// not_authorized
fblogin();
} else {
// not_logged_in
fblogin();
}
});
};
and also from normal LOGIN button which triggers the fblogin().
i don't see where your onclick code is or the action that calls fblogin() and i'm assuming the problem is when fblogin() gets called.
function fblogin(event) {
event.stopPropagation();
add an event parameter to each function fblogin(event) call so this can be cross browser compatible.
when an event occurs, it traverses to parent elements so they can inherit the event handler, in your case function fblogin(). when you stop propagation stopPropagation() you stop DOM traversing and the element that calls the function won't pass the handler to the parent if stopPropagation is set. that all means the browser will stop looping through all your DOM elements and making your jquery less recursive.

Why this Facebook javascript-sdk login code is automatically logging the user again and again?

Here I am unable to keep a user logged out once the user presses the logout button from my site. He is redirected to the login page but updateButton function is called again with same credentials he is getting logged in again. I tried several ways but the problem persists. I guess I am not doing things rightly in updateButton function down here and also FB.logout() is not being done correctly, as I get the error "FB.logout called without an access token" in the console.
The code is as follows:-
$(function(){
var button;
window.fbAsyncInit = function(){
FB.init({ appId : 'myAppId',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
function updateButton(response) {// I am not sure I am doing it right here
console.log("Update Button Fired.");
console.log(response);
button = document.getElementById('fb-auth');
if(response.status === 'connected')
{
FB.api('/me', function(info)
{
login(response,info);
});
}
else
{
FB.login(function(response)
{
if(response.status === 'not_authorized')
{
FB.api('/me', function(info){
login(response, info);
});
}
else
{
}
}, {scope:'email, user_birthday,user_about_me' });
}
}
}
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script');
e.async = true;
e.type = 'text/javascript';
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
})();
function login(response,info){
console.log('login Showloader called');
if (response.authResponse) {
var accessToken = response.authResponse.accessToken;
$.post("/web/register/faceBookRegistration",{ data:info,accessTokenValue:accessToken}).done( function(data){
if(typeof(data) != undefined){
window.location = "/web/login/loadViewFaceLogin";
}
});
}
}
function logout(response){
FB.logout(function(response){
console.log("User is now logged out");
});
}
});
Also I think my logout i.e
function logout(response){
FB.logout(function(response){
console.log("User is now logged out");
});
}
is not correct. In the console it shows that FB.logout called without an access token. What could be the reason
I took the liberty to rewrite your code, keeping your bases:
// File - fb-init.js
window.fbAsyncInit = function() {
FB.init({
appId : app_id,
status : false,
cookie : true,
xfbml : true
});
};
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
-
// File - main.js
$('#fb-login').on('click', function() {
FB.getLoginStatus(function(responseStatus) {
if (responseStatus.status === 'connected') {
FB.api('/me', function(responseMe) {
if (!responseMe.id)
return false;
var accessToken = responseMe.authResponse.accessToken;
$.post('/web/register/faceBookRegistration' {
data : responseMe,
accessTokenValue : accessToken
}).done(function(data) {
if (typeof(data) !== 'undefined')
window.location = '/web/login/loadViewFaceLogin';
});
});
}
else if (responseStatus.status === 'not_authorized') {
FB.login(function(responseLogin) {
FB.api('/me', function(responseMe) {
if (!responseMe.id)
return false;
var accessToken = responseMe.authResponse.accessToken;
$.post('/web/register/faceBookRegistration' {
data : responseMe,
accessTokenValue : accessToken
}).done(function(data) {
if (typeof(data) !== 'undefined')
window.location = '/web/login/loadViewFaceLogin';
});
});
}, {scope:'email, user_birthday,user_about_me' });
}
else
return false;
});
});
$('#fb-logout').on('click', function() {
FB.logout(function(responseLogout) {
});
});
Because of the status set to true. If the current user is already logged on Facebook, it forces his auto-login on the website.
Anyway, it's not a good idea to use the FB.logout(), except if you want to force the user to logout from Facebook (And not your website).
About the popup, I think it's because of FB.getLoginStatus(updateButton); which calls the function updateButton() on every page loads.
You should improve it through an onclick function.
As I saw this Post FB.logout() called without an access token it confirmed what I always was on my mind that my Logout is not being done properly. If that get done I would be okay.
Here is the logout function code which did it for me :-
function logout(response){
if(!response.authResponse){
window.location = "/web/login/";
return;
}
FB.logout(function(response){
FB.Auth.setAuthResponse(null,'unknown');
logout(response);
});
}
As in the above link its been said that we should be keep sending logout request till its destroyed at the Facebook side. I made it a recursive call and the way out was when the the check confirmed it.
I am a noob and would only be glad if somebody working on the present solution builds a more elegant hack.
Thanks to 'ZeNy' too.

Uncaught ReferenceError: FB is not defined when using FB.getLoginStatus

I'm trying to check if a user has logged in using facebook and get that error in JS console. My code looks like this:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = 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
});
};
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
</script>
What could be the problem and are there any sugestions on how to fix it?
In Chrome, you'd be getting the error: Uncaught ReferenceError: FB is not defined.
I like to trigger a custom event in Facebook's initialization function, fbAsyncInit().
Then I'm not limited to doing all my FB related scripting inside of the fbAsyncInit function. I can put it anywhere, by just listening for that custom event to be fired.
window.fbAsyncInit = function() {
FB.init({
appId : '123456789',
status : true,
cookie : true,
xfbml : true
});
$(document).trigger('fbload'); // <---- THIS RIGHT HERE TRIGGERS A CUSTOM EVENT CALLED 'fbload'
};
//MEANWHILE IN $(document).ready()
$(document).on(
'fbload', // <---- HERE'S OUR CUSTOM EVENT BEING LISTENED FOR
function(){
//some code that requires the FB object
//such as...
FB.getLoginStatus(function(res){
if( res.status == "connected" ){
FB.api('/me', function(fbUser) {
console.log("Open the pod bay doors, " + fbUser.name + ".");
});
}
});
}
);
You are calling FB.getLoginStatus before the SDK is loaded and/or initialized. To wait for that, that’s what the fbAsyncInit event is for. So put the method call in there.
I used the following simple approach and it works correctly:
In the head section I load the SDK:
<script type="text/javascript" src="//connect.facebook.net/en_US/sdk.js"></script>
Then in the body of your page where your actual content is, I used this:
<script>
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
FB.login(function(response) {
statusChangeCallback2(response);
}, {scope: 'public_profile,email'});
} else {
alert("not connected, not logged into facebook, we don't know");
}
}
function statusChangeCallback2(response) {
console.log('statusChangeCallback2');
console.log(response);
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
console.log('still not authorized!');
} else {
alert("not connected, not logged into facebook, we don't know");
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
function testAPI() {
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 + '!';
});
}
$(document).ready(function() {
FB.init({
appId : '1119999988888898981989819891',
xfbml : true,
version : 'v2.2'
});
checkLoginState();
});
</script>
Simply using script with facbook sdk directly in tag
<script type="text/javascript" src="//connect.facebook.net/en_US/all.js#xfbml=1&appId=YOUR_APP_ID" id="facebook-jssdk"></script>
We were facing the same issue, and since FB sdk was not loading (or loading with delays) this was causing problems (or breaking javascript)in some cases which were dependent upon that.
To resolve this issue, we delegated all the calls related to facebook.
We created a function like :
function callOnFBSDKLoad(callback){
if (window.isFBInitialized) {
callback();
}
else {
jQuery(document).bind('fbInitialized', callback);
}
}
Where fbInitialized is a custom event learn more about custom events here.
And window.isFBInitialized is a variable set when SDK is loaded.
callback is the method enclosing FB related events.
e.g.
var FBLogin = function(){
FB.login(...);
}
callOnFBSDKLoad(FBLogin)
PS:
Please ignore syntax and naming conventions, I am basically sharing the idea to resolve such issues.
A simpler and solid solution. Call a function when the SDK loads. I will name it triggerLoginCheck().
<script>
window.fbAsyncInit = function() {
FB.init({
//TO DO: Add your unique Facebook app ID (All numbers).
appId : '***unique_app_id***',
cookie : true,
xfbml : true,
version : 'v2.8'
});
//Call the function here
triggerLoginCheck();
FB.AppEvents.logPageView();
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
Later, anywhere, place this:
function triggerLoginCheck() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
console.log(response);
});
}
It's work fine for me. Is necessary include the Object "Log.info.bind".
var Log = { info: { bind: function(){ alert('Hi'); testAPI(); } } }

Facebook authentication won't work

My website is using Facebook Connect, but since a month it's not working. I suspect that Facebook changed something. I tried to find out, but it was impossible. I have a Java file that initiates the authentication, but I don't know if that file is the problem. Well, basically it connect, but it's not returning the registration form of my website.
window.fbAsyncInit = function() {
FB.init({appId: cfg_facebook_app_id, status: true, cookie: true, xfbml: true});
//initial login check
FB.getLoginStatus(function(response) {
if (response.session) {
//logged in, force logout
FB.logout(function() {
//logged out, subscribe to events
loginEvents();
});
} else {
//not logged in
loginEvents();
}
});
function loginEvents() {
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
logout();
});
FB.Event.subscribe('auth.login', function(response) {
login(response);
//login redirects the user. Before logout fires()
});
}
};
(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 login(){
FB.api('/me', function(response) {
window.location = cfg_site_url + 'facebook_auth.php?hashcode='+response.id;
});
}
try{} updating to the new version of javascript sdk https://developers.facebook.com/docs/reference/javascript/
As of December 13th, 2011, the JavaScript SDK now only supports OAuth
2.0 for authentication. The ability to enable OAuth 2.0 in the JS SDK was first introduced in July. All apps were given until October 1,
2011 to test and migrate. With this change, please ensure that you are
using FB.getAuthResponse to obtain the access token.

Categories