I am attempting to use Facebook's Javascript SDK to get a user's login status when my page is displayed.
The code I am using is as follows:
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
alert('Logged in');
} else {
alert('Need to log in!');
}
});
I go through the Facebook initialization without problems, and the FB.getLoginStatus() function gets called, but apparently the Facebook server does not respond. I do not receive a response of any kind.
I did put my application's ID into the initialization function, and the initialization code is downloaded from Facebook. I am debugging on Firefox using Firebug, so I know the initialization is successful and the FB.getLoginStatus() call is being made. I am simply not getting the response back from the server.
Can anyone suggest any reasons why I am not getting this response? If so, please advise.
ADDITION:
In response to Sahil Mittal's request, the entire code is provided below. It should be noted that there really isn't much more to see...
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : XXXXXXXXXXXX,
status : true,
xfbml : true
});
};
(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/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
alert('Logged in');
} else {
alert('Need to Log In');
}
});
</script>
<body>
<div id="fb-root"></div>
...
</body>
credit for this answer should go to CBroe. I wish that CBroe had put this as an answer so that I could give proper credit.
Nevertheless, the answer to this question is to place all FB functions inside the window.fbAsyncInit() function, as in the following example:
window.fbAsyncInit = function() {
FB.init({
appId : XXXXXXXXXXXXX,
status : false,
xfbml : true
});
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
alert('Logged in');
} else {
alert('Need to Log In');
}
});
};
This is not well documented on Facebook (what else is new???), so I am posting this so that other Facebook newbies can avoid the frustration and delay that I experienced.
Again: thanks should go to CBroe for this answer.
Related
I am Using Facebook JavaScript API to create login with feature with Facebook and fetch the user details from the API.
When I am using the same code in normal way, I am getting the data fetched from from Facebook api.
When I try to do the same thing with requireJS, I am Getting this error
"Uncaught TypeError: FB.login is not a function"
I have seen errors like undefined function but this new to me.
The format which I am following
https://developers.facebook.com/docs/javascript/howto/requirejs/v2.7
and my code fb.js goes here
define(['jquery','facebook'], function($,FB){
window.fbAsyncInit = function() {
FB.init({
appId : '89080988080545753578',
oauth : true,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true ,// parse XFBML
version : 'v2.5'
});
};
window.fb_login = function(){
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function(response) {
user_email = response.email; //get user email
$("#name").val(response.name);
$("#user-id").val(response.id);
if(response.gender == 'male') {
$('input[name="gender"][value="female"]').attr('checked', false);
$('input[name="gender"][value="male"]').attr('checked', true);
} else {
$('input[name="gender"][value="male"]').attr('checked', false);
$('input[name="gender"][value="female"]').attr('checked', true);
}
$("#birthday").val(response.birthday);
$("#email").val(response.email);
// you can store this data into your database
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'publish_stream,email'
});
};
});
and the html code for the button click
<button type="button" class="btn btn-lg btn-block sm fb" value="Login" id="FB">Facebook</button>
and JS code for the click event
$( document ).ready(function() {
$(".btn").click(function(){
//getting button id value in variable
var method = $(this).attr('id');
$("#sign_method").val(method);
if(method == 'FB') {
alert('Facebook');
fb_login();
//fbData();
//$("#signup").submit();
} else if(method == 'GP') {
alert('Google Plus');
login();
// $("#signup").submit();
} else {
alert('Email');
$("#signup").remove();
alert('form removed');
window.location.href = "signup.html";
}
});
The error message means that the JS SDK is not loaded yet. You are missing this in your code:
(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'));
FB.login must be used AFTER FB.init. Make sure FB.init gets called.
More information: http://www.devils-heaven.com/facebook-javascript-sdk-login/
For RequireJS, this would be the official way to include the JS SDK: https://developers.facebook.com/docs/javascript/howto/requirejs/v2.7#adding-a-shim-to-the-facebook-sdk
In my case, I had an adblocker extension that was preventing SDK from initializing properly. I only realized after trying in a different browser that didn't have adblocker extension
I have implemented a facebook login on my website, and authentication works fine. I can access my users name, but nothing else implying my permissions are not working correctly. I have tried a few fixes and looked around, but it seems like nothing is fixing it :/ Here is my code:
<div class="fb-login-button" data-max-rows="1" data-size="xlarge" data-show-faces="true" data-auto-logout-link="false" data-scope="public_profile,email,user_friends" onlogin="checkLoginState()";>
</div>
<script>
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
if (response.status === 'connected') {
loggedIn();
} else if (response.status === 'not_authorized') {
//User is logged into FB, but not my app
} else {
//User is not logged into FB
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'ID',
cookie : true,
xfbml : true,
version : 'v2.2'
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
(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>
If anyone could lend a hand that would be great :)
Thanks!
i see you have a LoggedIn(); but its not declared anywhere in your code yet
so do just that can call the FB.api from there.
Heres how:
*create LoggedIn(): I recommend after your checkLoginState();
function LoggedIn(){
FB.api('/me),function(response){
console.log(JSON.stringify(response));
});
}
//i assume u have firebug running, so from here u can view the info u asked permission for.
//Note that if you're running on local host, it will ony show ur id and name
to get other, you would have to display them manually: like this
FB.api('/me', {locale: 'tr_TR', fields: 'id,name,first_name,last_name,gender,age_range,link,locale,email'}, function(response) {
console.log(JSON.stringify(response));
console.log(response.name);
console.log(response.email);
});
Hope this is clear enough
Read up:
https://developers.facebook.com/docs/facebook-login/web#steps
I am using the Facebook SDK to retrieve the current logged in user on Facebook and output their name and e-mail address.
The issue I am having is when a user visits my page their name and e-mail address is automatically being displayed. I would like this to only happen if they click the Facebook log-in function.
My JS is:
function statusChangeCallback(response)
{
if (response.status === 'connected') {
updateUIWithFacebookFields();
}
}
function checkLoginState()
{
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function()
{
FB.init({
appId : 'snipped',
cookie : false,
xfbml : true,
version : 'v2.1'
});
FB.getLoginStatus(function(response)
{
statusChangeCallback(response);
});
};
(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'));
function updateUIWithFacebookFields()
{
FB.api('/me', function(response)
{
var registerUsernameElm = document.getElementById('username');
var registerUserEmailElm = document.getElementById('useremail');
if(registerUsernameElm)
{
registerUsernameElm.value = response.name;
}
if(registerUserEmailElm)
{
registerUserEmailElm.value = response.email;
}
});
}
And my button code is:
<fb:login-button scope="public_profile,email" size="large" onlogin="checkLoginState();"></fb:login-button></span>
How can I only have this run when the button is clicked?
Wow, I'm surprised nobody wanted to answer this. I had this same problem just a few minutes ago and searched for the same question. Since I find no answer to our exactly the same question, I tried to experiment on my own. So here is what I came up with but using your own example:
On this part of your code:
window.fbAsyncInit = function()
{
FB.init({
appId : 'snipped',
cookie : false,
xfbml : true,
version : 'v2.1'
});
FB.getLoginStatus(function(response)
{
statusChangeCallback(response);
});
};
I just removed the part FB.getLoginStatus since this will be called when you press the button. So your code becomes:
window.fbAsyncInit = function()
{
FB.init({
appId : 'snipped',
cookie : false,
xfbml : true,
version : 'v2.1'
});
};
That's it!
It was a simple solution that I can think of so I'm not sure if it is the best practice. Since this question is 2 months old, you probably found your own solution by now, kindly to share what you did so I can be assured if what I did is correct. Thanks!
All I want is to use alert to display the name of the logged in user and prompt the user to login if not logged in.
Please help, I've been online for about 4 hrs not getting the facebook graph api
this is the code from facebook.com
i do not know exactly how to manipulation this code. i have tried to add three lines towards the end...
<script>
function statusChangeCallback(response){
console.log('statusChangeCallback');
console.log(response);
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
document.getElementById('status').innerHTML = 'Please log ' + 'into this app.';
} else {
document.getElementById('status').innerHTML = 'Please log ' + 'into Facebook.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : '1608304139394721',
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse social plugins on this page
version : 'v2.0' // use version 2.0
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(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'));
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 + '!';
name=response.name;
alert(name);
});
}
</script>
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();"></fb:login-button>
I added these 2 lines to the code above but it doesn't even login. Also, it doesn't alert the user's name.
name=response.name;
alert(name);
Your code is valid and works fine, in JavaScript code is being executed line after line while it stops executing whenever there's an error(s) on the current line which is being executed, your error is:
as you can in your code your alert(name) comes after that line which occurred that error
Solution
pretty simple add an element (div) with id status to your document to avoid that error
<div id="status"></div>
or use jQuery as a DOM selector
I am trying to create a simple FB login that will request email permission...
The second block is working just fine using button option #2,
But second block using button option #1 does not call authUser() function,
& when I try to use the first block for the same result it does not work either.
Why is the FIRST BLOCK not calling authUser() function??
Is it because of the login button type?
If so, how can I use button option #1 so to enable data-auto-logout-link="true"?
When using button option #2 in SECOND BLOCK the onClick() function is not called either...why?
I can already assume that the facebook button type is causing this and over looking the premissions request in the code...
both blocks are in the same <script type="text/javascript"> tag
FIRST OPTION
FB.init({
appId : 'YOUR_APP_ID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Check if the current user is logged in and has authorized the app
FB.getLoginStatus(checkLoginStatus);
// Login in the current user via Facebook and ask for email permission
function authUser() {
console.log("--- authUser ---");
FB.login(checkLoginStatus, {scope : 'email'});
}
// Check the result of the user status and display login button if necessary
function checkLoginStatus(response) {
if(response && response.status == 'connected') {
console.log('User is authorized');
} else if (response.status === 'not_authorized') {
console.log('User is not_authorized ... ');
} else {
console.log('User is not authorized');
document.getElementById('loginButton').style.display = 'inline-block';
}
}
Button:
<div class="fb-login-button" id="loginButton" data-max-rows="1" data-size="medium" data-show-faces="false" data-auto-logout-link="true" onclick="authUser();"></div>
SECOND OPTION
window.onload = function() {
document.getElementById('fb-login').onclick = function() {
var cb = function(response) {
console.log('FB.login callback', response);
if (response.status === 'connected') {
console.log('User logged in');
} else {
console.log('User is logged out');
}
};
FB.login(cb, { scope: 'email' });
};
}
With 2 options for buttons:
<fb:login-button id="fb-login" data-max-rows="1" data-size="medium" data-show-faces="false" data-auto-logout-link="true"></fb:login-button>
<button id="fb-login">FaceBook Login</button>
not using the same button ids in real code, this is just for example
Thanx.
I never tried, but it might be helpful.
Facebook for Developers
The special part for JavaScript:
Facebook for Developers - JavaScript
you can find some solution here
<div id="fb-root"></div>
<script>
(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/all.js#xfbml=1&appId=xxxxxxxxxxx";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function loginfb() {
FB.init({
appId:'xxxxxxxxxxxxxxxx',
cookie:true,
status:true,
xfbml:false
});
FB.login(function(responses) {
if(responses.authResponse)
{
FB.api('/me?fields=email,name', function(response) {
alert(response.email);
});
}
});
}
</script>