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.
Related
I am using Facebook API to log in a user. It logs in a user successfully.
But whenever I refresh the website or close it then reopen it logs out automatically. I don't need that I want a user logged in until he himself logs out of my website. How do I do it?
This is my code:
function statusChangeCallback(response) {
if (response.status === 'connected') {
setElements(true);
console.log('Logged in');
instaInfo();
} else {
setElements(false);
console.log('not logged in');
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
function setElements(isLoggedIn) {
if (isLoggedIn) {
document.querySelector('#fb-btn').style.display = 'none';
document.querySelector('.logout').style.display = 'block';
document.querySelector('.navigation').style.display = 'block';
document.querySelector('.nav-main').style.visibility = 'visible';
document.querySelector('#container').style.display = 'block';
} else {
document.querySelector('#fb-btn').style.display = 'block';
document.querySelector('.logout').style.display = 'none';
document.querySelector('.navigation').style.display = 'none';
document.querySelector('.nav-main').style.visibility = 'hidden';
document.querySelector('#container').style.display = 'none';
}
}
document.querySelector('.logout').addEventListener('click', () => {
FB.logout(function() {
setElements(false);
console.log('Logged Out!');
});
});
According to the facebook documentation:
While you can call FB.getLoginStatus any time (for example, when the
user tries to take a social action), most social apps need to know the
user's status as soon as possible after the page loads. In this case,
rather than calling FB.getLoginStatus explicitly, it is possible to
check the user's status by setting status: true when you call FB.init.
To receive the response of this call, you must subscribe to the
auth.statusChange event. The response object passed by this event is
identical to that which would be returned by calling FB.getLoginStatus
explicitly.
https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
It might just be that you're running into a problem with the asynchronous nature of javascript in your code example. Have you checked what your call on getLoginStatus actually returns?
You can take advantage of the browser's localStorage (it' s a method of the window object) to keep the data even after reloading the page or even after closing the window.
Take a look here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
I have a series of buttons that execute different functions when clicked. The function checks whether the user is logged in, and if so proceeds, if not it displays an overlay with ability to log in/create account.
What I want to do is re-execute the button click after log-in, without the user having to reclick it.
I have it working at the moment, but I'm pretty sure that what I'm doing isn't best practice, so looking for advice on how I can improve...
Here's what I'm doing: setting a global variable "pending_request" that stores the function to be re-run and in the success part of the log-in ajax request calling "eval(pending_request)"
Example of one of the buttons:
jQuery('#maybe_button').click(function() {
pending_request = "jQuery('#maybe_button').click()"
var loggedin = get_login_status();
if (loggedin == true) {
rec_status("maybe");
}
});
.
success: function(data) {
if(data === "User not found"){
alert("Email or Password incorrect, please try again");
}else{
document.getElementById('loginscreen').style.display = 'none';
document.getElementById('locationover').style.display = 'none';
eval(pending_request);
pending_request = "";
}
}
Register a function to handle the click and then invoke that func directly without eval().
jQuery('#maybe_button').on('click', myFunction)
This executes myFunction when the button is clicked. Now you can "re-run" the function code every time you need it with myFunction().
And btw since you are using jQuery you can do $('#loginscreen').hide() where $ is an alias for jQuery that's auto defined.
EDIT
Please, take a look at the following code:
var pressedButton = null;
$('button1').on('click', function() {
if (!isLoggedIn()) {
pressedButton = $(this);
return;
}
// ...
});
And, in your success handler:
success: function() {
// ...
if (pressedButton) pressedButton.trigger('click');
// ...
}
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!
I have a link to login with facebook on my page and I want to manipulate the way the onclick works. Currently I have changed it so that it does not do the default action by adding return false to the end:
$('#login').on('click', function(e) {
FB.login(function(response) {
//window.easyUserData.login = response;
if (response.authResponse) {
console.log('authorised');
return true;
} else {
// cancelled
}
});
return false;
});
What was happening was that right after it called FB.login to open the dialog it would redirect the page, not what I wanted. What i am looking for is for it to do the default action of the link where i put return true. The return true bit doesn't work because by the time it gets there, return false has already been processed. Any tips on how to do this?
The link has href="#/home" and I am using backbone.js to handle routing.
Due to asynchronous nature of your login function you would have to use a javscript redirect:
$('#login').on('click', function(e) {
var href=this.href;
FB.login(function(response) {
//window.easyUserData.login = response;
if (response.authResponse) {
console.log('authorised');
/* redirect here*/
window.location=href;
} else {
// cancelled
}
});
return false;
});
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);
});
}
});