Facebook Connect does not process jQuery ajax call after successful login - facebook

I've got the following script:
<script>
window.fbAsyncInit = function () {
FB.init({ appId: '<%: Facebook.FacebookApplication.Current.AppId %>',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
function FBLogin() {
FB.login(function (response) {
if (response.authResponse) {
ConnectFacebookUser(response.authResponse.accessToken);
} else {
alert('User cancelled login or did not fully authorize.');
}
}, { scope: 'email' });
}
$('#fb-button').live('click', function (e) {
FBLogin();
e.preventDefault();
});
function ConnectFacebookUser(at) {
var postdata = "at=" + at;
alert('This is the access token : ' + at);
$.ajax({
type: "POST",
dataType: "json", // what data type to expect from the server
url: "/FBConnect.ashx",
data: postdata,
success: function (data) {
// do nothing
alert('all good');
},
error: function (xhr, status, error) {
alert('error occured in FBConnect.ashx');
}
});
alert('finished');
}
};
(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 for the html fragment:
Login with facebook
<div id="fb-root"></div>
When the link is clicked, a popup window for facebook shows up and when i enter my login details, i only see an alert to say "This is the access token..." but the rest of the code don't get processed. If I click the "login with facebook" link one more time, then everything gets processed as normal.
What could be the problem?

It works for me. I get the message 'this is the acccess code' and then i get a 'finished' alert. Check your Chrome debugger tools to look for any script errors that may be occuring silently.

Check out https://github.com/xocialhost/jquery.xocialCore.js/blob/master/jquery.xocialCore.js to see a jQuery specific way of doing this. One thing I noticed is that the jQuery click function when calling the FB.login was triggering the popup blocker in a few browsers I was testing with. I set this up to work around that issue but it's also a way to add a callback that is run properly during the init sequence.

Related

API Error Description: Session key invalid or no longer valid (error 102)

I cant figure out why facebook publish is not working on this site
I get
API Error Code: 102
API Error Description: Session key invalid or no longer valid
Error Message: Iframe dialogs must be called with a session key
While calling the stream.publish method as iframe
<script type="text/javascript">
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/fr_FR/all.js';
document.getElementById('fb-root').appendChild(e);
}());
window.fbAsyncInit = function()
{
FB.init({ appId: '303380259758621',
status: true,
channelUrl: 'http://www.crabegame.com/channel.php',
cookie: true,
xfbml: true,
oauth: true});
}
function PublishStream(score)
{
FB.ui(
{
method: 'stream.publish',
display : 'iframe',
message : '',
attachment:
{
name: 'CrabeGame',
caption: 'Essaye de battre mon score sur le Crabe Game !',
description: "J'ai réalisé un score de " + score + "points au Crabe Game !",
href: 'http://www.crabegame.com',
media:
[
{
type: 'image',
src: 'http://crabegame.com/media/crabe_fb.png',
href: 'http://www.crabegame.com'
}
]
},
action_links:
[
{
text: 'Play Crabe Game',
href: 'http://www.crabe-game.com'
}
],
user_message_prompt: 'Publier sur votre mur'
},
function (response)
{
if (response && response.post_id)
{
}
}
);
}
</script>
This means that you have no current user. Try this in order to call PublishStream:
FB.login(function(response) {
if (response.authResponse) {
PublishStream();
} else {
console.log('Not logged in');
}
});
you don´t need a logged in user, just remove display: "iframe", worked for me. it will still show in an iframe, but without error. don´t ask me why, with 1:1 the same app settings it works WITH the display value in another app of mine...at least that worked for me with the apprequest dialog, might be the same here.
and i would use "feed" instead of "stream.publish".
see here: https://developers.facebook.com/docs/reference/dialogs/feed/
also: Using Like Button and FB.ui (apprequests) On the Same Page Conflicts

FB is not defined in Facebook Login

I have the following code but the FB.login gives a FB is not defined javascript error.
What am I missing?
<html>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function()
{
FB.init
({
appId : 'XXXX',
status : true,
cookie : true,
xfbml : true
});
};
(function()
{
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
FB.login(function(response)
{
if(response.session)
{
if(response.perms)
{
alert('yippee');
}
else
{
alert('oh no');
}
}
else
{
alert('login silly');
}
}, {perms:'email,user_birthday'});
</script>
hello
<fb:login-button></fb:login>
</body>
</html>
The function assigned to window.fbAsyncInit is run as soon as the SDK is loaded. Any code that you want to run after the SDK is loaded should be placed within this function and after the call to FB.init. For example, this is where you would test the logged in status of the user or subscribe to any Facebook events in which your application is interested.
Try by keeping other initialization code in between inialization and login function
Or keep FB.login code in $(document).ready
$(document).ready(function(){
FB.login(function(response)
{
if(response.session)
{
if(response.perms)
{
alert('yippee');
}
else
{
alert('oh no');
}
}
else
{
alert('login silly');
}
}, {perms:'email,user_birthday'});
});
You should not call to FB.login before JS-SDK is loaded, window.fbAsyncInit designed especially for this. If you move this call to be within window.fbAsyncInit function you'll be fine but be aware of fact that calling to FB.login opens popup, doing this without user interaction will be probably blocked by most browsers. If you want to use FB.login to handle login, you must do it on click or sumbit events...
BTW, you already have fb:login-button which is doing login once user clicks on it.
You can also get this error if you try to launch the facebook example code on your machine (e.g. copying the code in a .html file and trying to open it in your browser). You will need to upload this to your server and run it from there.

Problem with the redirections of apprequest in php

I am using the code below to send an app request to someone.
It works fine; it displays in Facebook notification.
when I click that notification, it redirects to the facebook app page.
I'm unable to make it redirect to the page which exists list of facbook app requests.
How do I make it redirect there?
is there any need to do changes in my facebook app setting ?
<div id="fb-root"></div>
<script>
function FacebookIframeAuthenticator(){
window.fbAsyncInit = function() {
FB.init({
appId: '123456789',
status: true,
logging: false,
cookie: false,
xfbml: true
});
FB.Canvas.setSize({height: 2000});
FB.Canvas.scrollTo(0,0);
FB.Canvas.setAutoResize();
};
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);
}
new FacebookIframeAuthenticator();
function sendInvReq ( friendUid, event ){
FB.ui({
method: 'apprequests',
message: 'I\'d like you to join my professional network on SITE NAME .- DB',
to: friendUid,
data: ''
}
, function(r){
if (r != null && typeof(r) != 'undefined'){
if (r.request_ids){
FB.api('/me/apprequests/?request_ids='+toString(request_ids));
$.ajax({
url: 'http://exapmple.com',
cache:false,
type:'POST',
data:({requestIds: r.request_ids.join(','), x_csrf: csrf}),
dataType: 'json',
complete: function(transport){}
});
}
}
}
);
}
</script>
in your developers page (https://developers.facebook.com/apps/your_app_id/advanced) you must change your application advanced settings "Upgrade to Requests 2.0" to disable
If I understood your question right: you can't control the notification url. It will always automatically redirect to your app url with one or more request_ids as paramter. The only possibility to redirect to your prefered destination is to look for this parameter and react properly.

Custom login button VS. fbml button

For a few days i was trying to use a custom button to invoke login
$(".join").live("click", login);
function login(){
FB.login(function(response) {
if (response) {
console.log('Login success.');
FB.api("/me", handleMe);
}
else {console.log('Login cancelled.')}
});
}
function handleMe(response) {
$.ajax({
async: 'false',
type: 'GET',
url: 'www. address.com',
data:
"uid=" + response.id +
"&name=" + response.name,
success: function(){
console.log('Ajax successful.');
console.log("<?php echo $this->session->userdata('fb_uid'); ?>");
window.location = "www. address.com";
},
error: function(){console.log('Ajax failed.');}
});
}
$(".join,.log,.biggie-btn").live("click", login);
However it was always buggy, the login window would not close (oddly, most of the times) and after I closed it, I would not get the user FB.API details, and I had to refresh the page to get them.
As soon as I switched to the bugs were gone (having exactly the same functionality), however I can't control now the style of the login button.
Is there a solution, to have a fully functional custom login button?
You can use the Facebook javascript SDK and easily build your own login button. Just have the button class FB.login and pass it a callback function and optionally any extended permissions you need. Upon success, this will set a cookie that has an access_token that you can use from server code if needed. Otherwise, you can just call javascript sdk functions.
Here is an example:
<!DOCTYPE html>
<html>
<body>
<div id="fb-root"></div>
Custom Login Button
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({ appId: 'your app id', status: true, cookie: true, xfbml : true });
function doLogin() {
FB.login(function(response) {
if (response.session && response.perms) {
FB.api('/me',
function(response) {
alert('User: ' + response.name);
alert('Full details: ' + JSON.stringify(response));
}
);
}
} , {perms:'user_about_me'});
}
</script>
</body>
</html>

Facebook Graph API: FB.login() called before calling FB.init()

I'm trying to use the new Facebook Graph API on my website. This is what I have:
Somewhere on the page:
<fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button>
Right after the tag:
<div id="fb-root">
</div>
<script type="text/javascript">
window.fbAsyncInit = function () {
FB.init({ appId: '<%= ConfigurationManager.AppSettings["FBAppId"] %>', status: true, cookie: true, xfbml: true });
/* All the events registered */
FB.Event.subscribe('auth.login', function (response) {
// do something with response
alert("login success");
});
FB.Event.subscribe('auth.logout', function (response) {
// do something with response
alert("logout success");
});
FB.getLoginStatus(function (response) {
if (response.session) {
// logged in and connected user, someone you know
alert("login success");
}
});
};
(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);
} ());
</script>
but when I click on the generated login button, nothing happens.
In addition, I'm getting
FB.getLoginStatus() called before calling FB.init().
in Firebug console.
Any ideas?
I can't believe it, I was referencing a non existing key in the Web.config hence FB.init was failing silently.
It works as expected now.
To be clearer I wasn't passing the appId to FB.init, once I did, it worked.
Had the same issue, here is the solution that worked for me. Just put the following in your head section or in other words, add the app_id to the source of the facebook js.
<script src="//connect.facebook.net/en_US/all.js&appId=xxxxxxxxxxxxxxx" type="text/javascript"></script>
In my case, the problem went away after I disabled the XFBML functionality (i.e. setting the xfbml key to false, removing the fb: namespace and the #xfbml=1 fragment in <script src="…">). Good that I didn’t need it anyway.
YMMV, there are several other valid reasons why this error message can appear.