Facebook JavaScript SDK Login - javascript

Here's my code. It works perfectly on Facebook's JavaScript SDK test console, but not here : http://www.booktrolley.in/beta/fblogin.php
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head></head>
<body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : '270423476307006',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
channelUrl : 'http://pedurology.org/booktrolley/beta/channel.html', // channel.html file
oauth : true // enable OAuth 2.0
});
</script>
<h1>Login, Logout, Name and Profile Picture</h1>
<div id="account-info"></div>
<script>
/**
* This assumes the user is logged in and renders their profile picture,
* name and a logout link.
*/
function showAccountInfo() {
FB.api(
{
method: 'fql.query',
query: 'SELECT name,uid,pic_square FROM user WHERE uid='+FB.getSession().uid
},
function(response) {
alert(FB.getSession().uid);
Log.info('API Callback', response);
document.getElementById('account-info').innerHTML = (
'<img src="' + response[0].pic_square + '"> ' +
response[0].name +
' <img onclick="FB.logout()" style="cursor: pointer;"' +
'src="https://s-static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">'
);
}
);
}
/**
* This assumes the user is logged out, and renders a login button.
*/
function showLoginButton() {
document.getElementById('account-info').innerHTML = (
'<img onclick="FB.login()" style="cursor: pointer;"' +
'src="https://s-static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">'
);
}
/**
* This will be called once on page load, and every time the status changes.
*/
function onStatus(response) {
Log.info('onStatus', response);
if (response.session) {
showAccountInfo();
} else {
showLoginButton();
}
}
FB.getLoginStatus(function(response) {
onStatus(response); // once on page load
FB.Event.subscribe('auth.statusChange', onStatus); // every status change
});
</script>
</body>
</html>

I'm getting a "Log is undefined" error in the following code:
function onStatus(response) {
Log.info('onStatus', response);
if (response.session) {
showAccountInfo();
} else {
showLoginButton();
}
}
FB.getLoginStatus(function(response) {
onStatus(response); // once on page load
FB.Event.subscribe('auth.statusChange', onStatus); // every status change
});
you trying to make use of a logger that exists on FB's page, but not on your own?

Try this code:
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head></head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '270423476307006',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
FB.getLoginStatus(function(response) {
onStatus(response); // once on page load
FB.Event.subscribe('auth.statusChange', onStatus); // every status change
});
};
(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>
<h1>Login, Logout, Name and Profile Picture</h1>
<div id="account-info"></div>
<script>
/**
* This assumes the user is logged in and renders their profile picture,
* name and a logout link.
*/
function showAccountInfo(resp) {
if( !resp.userID ) {
// we shouldn't be here
return;
}
FB.api(
{
method: 'fql.query',
query: 'SELECT name,uid,pic_square FROM user WHERE uid='+resp.userID
},
function(response) {
document.getElementById('account-info').innerHTML = (
'<img src="' + response[0].pic_square + '"> ' +
response[0].name +
' <img onclick="FB.logout()" style="cursor: pointer;"' +
'src="https://s-static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">'
);
}
);
}
/**
* This assumes the user is logged out, and renders a login button.
*/
function showLoginButton() {
document.getElementById('account-info').innerHTML = (
'<img onclick="FB.login()" style="cursor: pointer;"' +
'src="https://s-static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">'
);
}
/**
* This will be called once on page load, and every time the status changes.
*/
function onStatus(response) {
if (response.authResponse) {
showAccountInfo(response.authResponse);
} else {
showLoginButton();
}
}
</script>
</body>
Now let's explain what we've done:
We are using Asynchronous loading to insure that FB.getLoginStatus() will get fired ONLY when the library is successfully loaded
Since you are setting oauth to true then you need to change your code to work with the new responses (refer to this post) (you may need to change your app settings)
Based on #2, the current user ID to use in your showAccountInfo() will be accessible using response.authResponse.userID

Related

Facebook Registration - Reading the data/signed request with Javascript

I am able to get the registration form working with custom fields and retrieve the custom fields via a cookie on the redirect page. What I cannot figure out is how to retrieve the Facebook info (name,email,birthday) on the next page (I'm not a PHP guy). I have been over the documentation several times, the "reading the data" section (FB Documentation), and scoured the internet but can only find PHP and C# solutions.
I am looking for a javascript, jQuery, or ColdFusion solution if someone could help me out.
Below is my code as a quick reference. As it stands Page 2 just dumps out the cookie information.
Page 1
<html>
<head>
<title>My Facebook Login Page</title>
</head>
<body>
<!--- Facebook Call --->
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'myAppID', // App ID
channelUrl : 'http://.../channel.html', // Channel File
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', 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));
</script>
<!--- Output Facebook Box--->
<fb:registration redirect-uri="http://.../page2.cfm"
fields='[
{"name":"name"},
{"name":"email"},
{"name":"displayName","description":"Display Name:", "type":"text"},
{"name":"location"},
{"name":"birthday"}
]'
onvalidate="validateAndSave">
</fb:registration>
<!---Validation + set Cookie --->
<script>
function validateAndSave(form) {
if (!form.displayName) {
return({"displayName":"Display Name is Required"});
}
document.cookie = 'fbInfo='+'displayName='+form.displayName;
return {};
}
</script>
</body>
Here is my implementation based on trial and error with the FB javascript API.
function checkFB()
{
if (typeof(FB) === "undefined")
{
var t = setTimeout("checkFB()", 1000);
if (debug) console.log("FB is still undefined, try again in 1 second.");
}
else
{
if (debug) console.log("FB is defined, try to login -> ");
//Function to check the current login status of facebook
FB.getLoginStatus(function(r)
{
if (r.status === "not_authorized")
{
if (debug) console.log("-> NOT AUTHORIZED ");
}
else if (r.status === "connected")
{
if (debug) console.log("-> connected ");
if (r.authResponse)
{
FB.api('/me', function(rr) {
document.getElementById("fbFname").value = rr.first_name;
document.getElementById("fbLname").value = rr.last_name;
document.getElementById("fbEmail").value = rr.email;
document.getElementById("fbID").value = rr.id;
document.getElementById("status").value = "OK";
});
submitFB();
}
else
{
document.getElementById("status").value = "NOT AUTHORIZED";
history.go(-1);
if (debug) console.log("NOT AUTHORIZED");
}
}
else
{
if (debug) console.log("-> not connected -> POP UP BOX expected ");
// start login process
FB.login(function(re)
{
if (re.authResponse)
{
FB.api('/me', function(rr) {
document.getElementById("fbFname").value = rr.first_name;
document.getElementById("fbLname").value = rr.last_name;
document.getElementById("fbEmail").value = rr.email;
document.getElementById("fbID").value = rr.id;
document.getElementById("status").value = "OK";
});
submitFB();
}
else
{
document.getElementById("status").value = "NOT AUTHORIZED";
history.go(-1);
if (debug) console.log("NOT AUTHORIZED");
}
},
{scope: 'email'}); // we define what information we want to get from the user
}
});
}
}
I hope you have already gotten an appID from facebook and have a channel file, they need to replace 'myAppID' and 'http://.../channel.html'.
FB.init({
appId : 'myAppID', // App ID
channelUrl : 'http://.../channel.html', // Channel File

javascript sdk is opening multiple login dialogs

Im having an issue where the Javascript SDK opens multiple dialogs to log in.
if i log in and then out it works fine, but the next time i log in it will open 2 popups. next time it will open 3 and so on.
The Page is using PHP, Javascript/Jquery
The code is a tweaked version of this tutorial
http://thinkdiff.net/facebook/new-javascript-sdk-oauth-2-0-based-fbconnect-tutorial/
Here is my Code:
<div id="fb-root"></div>
<script type="text/javascript">
var button;
window.fbAsyncInit = function() {
FB.init({ appId: '<?php echo $facebook->getAppID() ?>',
status: true,
cookie: false,
xfbml: true,
oauth: true});
function updateButton(response) {
if (response.authResponse) {
$('#loged').hide();
$('#logged').show();
//user is already logged in and connected
FB.api('/me', function(info) {
login(response, info);
});
$("#logged").click(function() {
FB.logout(function(response) {
logout(response);
});
});
} else {
//user is not connected to your app or logged out
$('#logged').hide();
$('#loged').show();
$("#loged").click(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_likes'});
})
}
}
// 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) {
$('#loged').hide();
$('#logged').show();
showLoader(false);
}
}
function logout(response){
showLoader(false);
}
//shows ajax loader
function showLoader(status){
if (status)
document.getElementById('loader').style.display = 'block';
else
document.getElementById('loader').style.display = 'none';
}
</script>
<img id="loged" src="img/in.png"/>
<img id="logged" hidden="hidden" src="img/out.png"/>
<div id="loader" style="display:none">
<img src="img/ajax-loader.gif" alt="loading" />
</div>
<br />
<div id="user-info"></div>
<br />
<div id="debug"></div>
if i log in and then out it works fine, but the next time i log in it will open 2 popups. next time it will open 3 and so on.
Are you staying on the same page – without reloading it in between?
That would explain what you’re describing, because then every time your function updateButton is called and goes into the else branch, it will add a new additional click event handler to #loged, so they would start “accumulating”, and therefor FB.login will be called multiple times – because each single click will trigger multiple handlers (that all do the same stuff).

Redirect URI using the Javascript SDK after authentication

So I've set up a basic login/authentication flow on the home page of my site. After the authentication dialog, I want to redirect them to another page on my site. I've tried several variations of the existing code, changing the site url under basic settings in the developer app, trying different oauth flows, and still, it simply redirects to the same homepage they logged in on. I know this sounds tremendously easy but there are so many different authentication flows and implementations that it's a bit confusing.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXX', // App ID
channelURL : '//localhost/dataweavr/channel.php', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
// Additional initialization code here
};
// 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));
</script>
And then some more fun...
<div id="fb-root"></div>
<div id="user-info"></div>
<button id="fb-auth">Login</button>
<script>
window.fbAsyncInit = function() {
FB.init({ appId: 'XXXXXXXXXXXXXXXXXXXXXX',
status: true,
cookie: true,
xfbml: true,
oauth: true});
function updateButton(response) {
var button = document.getElementById('fb-auth');
if (response.authResponse) {
//user is already logged in and connected
var userInfo = document.getElementById('user-info');
FB.api('/me', function(response) {
userInfo.innerHTML = '<img src="https://graph.facebook.com/'
+ response.id + '/picture">' + response.name;
button.innerHTML = 'Logout';
});
button.onclick = function() {
FB.logout(function(response) {
var userInfo = document.getElementById('user-info');
userInfo.innerHTML="";
});
};
} else {
//user is not connected to your app or logged out
button.innerHTML = 'Login';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
var userInfo = document.getElementById('user-info');
userInfo.innerHTML =
'<img src="https://graph.facebook.com/'
+ response.id + '/picture" style="margin-right:5px"/>'
+ response.name;
});
} else {
//user cancelled login or did not grant authorization
}
}, {scope:'email,user_birthday'});
}
}
}
// 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);
}());
</script>
And another unrelated issue. Why do I only have a normal button popup? How can I get the SDK to render a Facebook login button rather than just a simple login button?
You should be able to redirect the user after the login response. Under these lines:
FB.login(function(response) {
if (response.authResponse) {
Add something like this:
window.top.location = "http://page_to_redirect";
The button thing, hmm... well, you are writing a simple login button in the html, if you want a login button, change this:
Login
To this:
<fb:login-button></fb:login-button>
Hope it helps.

Facebook registration issue

I am showing the facebook registration iframe in thick box (Iframe inside iframe).
(If user is not logged in, button will be shown to login or else registration form will be shown directly.)
Crom is caching data. Because of that after login to facebook it shows error like "invalid client_id" (It doesn't shows me registration form). If I reload the parent iframe ie. thickbox window registration form shows fine.
I want to reload the thickbox iframe after login to facebook. I can get this control some how?. Is there any JS code available for this ?
Here is my code
<div id="content">
<div class="reg-cont">
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $this->facebookAppId; ?>',
status : true,
cookie : true,
xfbml : true
});
FB.getLoginStatus(function(response) {
if (response.status == "connected") {
window.location = "/facebook-login?facebook_uid=" + response.session.uid;
}
});
};
</script>
<fb:registration
fields="[
{'name':'name'},
{'name':'email'},
{'name':'church', 'description':'Home Church', 'type':'select', 'options':<?php echo str_replace('"', "'", $this->church); ?>, 'default':'none'},
{'name':'host', 'description':'Check this box if you are hosting your small group', 'type':'checkbox'}
]"
redirect-uri="http://<?php echo $_SERVER['SERVER_NAME']; ?>/User/index/create-facebook-account"
fb_only="true"
width="530">
</fb:registration>
</div>
</div>
Reload a targeted iframe on login. You will need to set the link, and frame name below
FB.Event.subscribe('auth.login', function(response) {
top.frames['YourFrameName'].location.href = 'http://example.com/';
});
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $this->facebookAppId; ?>',
status : true,
cookie : true,
xfbml : true
});
FB.getLoginStatus(function(response) {
if (response.status == "connected") {
window.location = "/facebook-login?facebook_uid=" + response.session.uid;
}
});
FB.Event.subscribe('auth.login', function(response) {
top.frames['YourFrameName'].location.href = 'http://example.com/';
});
};
</script>

Facebook Opengraph customize fb login button

I'm using facebook open graph, new api, and i can do this:
<fb:login-button show-faces="true" max-rows="9" perms="email" autologoutlink="true" onlogin="window.location = 'http://www.example.com/facebook/facebook_test/'"></fb:login-button>
but when i read the doc if i need more options in http://developers.facebook.com/docs/reference/javascript/FB.login says i can:
FB.login(function(response) {
if (response.session) {
if (response.perms) {
// user is logged in and granted some permissions.
// perms is a comma separated list of granted permissions
} else {
// user is logged in, but did not grant any permissions
}
} else {
// user is not logged in
}
}, {perms:'read_stream,publish_stream,offline_access'});
but if i need another image for fb button, and if i need another things, i can't find how do that, of in what part of html i can call FB.login, is between tags 'script'?
You need to use Javascript SDK for this. Just wrap that FB.login into some function and call it wherever you want. For example if you want to call it on image click:
<html>
<head>
</head>
<body>
<div id="fb-root"></div>
<script>
//initializing API
window.fbAsyncInit = function() {
FB.init({appId: 'your app id', status: true, cookie: true,
xfbml: true});
};
(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>
<!-- custom login button -->
<img src="images/my_login.png">
<script>
//your fb login function
function fblogin() {
FB.login(function(response) {
//...
}, {scope:'read_stream,publish_stream,offline_access'});
}
</script>
</body>
</html>

Categories

Resources