I am working on a android phonegap application with facebook integration.
FB.login(function(response) function has a response handler it is being called when
user click on fb button, but its not getting into the function response
or alert('test') every time. it gets into this script only when i hit
around 5 or 6 times. wat i need is to fetch the access token the very first time i logged into facebook. i have gone through a lot of links regarding this but
cant find an exact solution for this...
FB login callback function not responding if user is already logged in facebook
Even this question seems to be same but i cant figure it out my solution.
this is the code am working :
<div id="data">Hello Facebooktesters, loading ...</div>
<button onclick="login()">Login</button>
<button onclick="me()">Me</button>
<button onclick="logout()">Logout</button>
<button onclick="Post()">facebookWallPost</button>
<script type="text/javascript">
document.addEventListener('deviceready', function() {
try {
alert('Device is ready! Make sure you set your app_id below this alert.');
FB.init({
appId : "xxxxxxxxxxxxxxx",
nativeInterface : CDV.FB,
useCachedDialogs : false
});
document.getElementById('data').innerHTML = "FB init executed";
} catch (e) {
alert(e);
}
}, false);
function me() {
FB.api('/me/friends', {
fields : 'id, name, picture'
}, function(response) {
if (response.error) {
alert(JSON.stringify(response.error));
} else {
var data = document.getElementById('data');
fdata = response.data;
console.log("fdata: " + fdata);
response.data.forEach(function(item) {
var d = document.createElement('div');
d.innerHTML = "<img src="+item.picture+"/>" + item.name;
data.appendChild(d);
});
}
var friends = response.data;
console.log(friends.length);
for ( var k = 0; k < friends.length && k < 200; k++) {
var friend = friends[k];
var index = 1;
friendIDs[k] = friend.id;
//friendsInfo[k] = friend;
}
console.log("friendId's: " + friendIDs);
});
}
function login() {
FB.login(function(response) {
alert('test');
if (response.authResponse) {
alert('logged in');
var access_token = FB.getAuthResponse()['accessToken'];
alert(access_token);
window.location = "test.html"
} else {
alert('not logged in');
}
}, {
scope : "email"
});
}
function logout() {
alert('test');
FB.logout(function(response) {
alert('logged out');
//window.location.reload();
});
}
function Post(ele) {
var domain = 'http://192.168.0.46:8082/';
console.log('Debug 1');
var params = {
method: 'feed',
name: 'test - test',
link: domain+'test/test/showproddetails.action?product.productId=1',
picture: 'http://www.careersolutions.com/test.png',
caption: 'test',
description: 'test'
};
console.log(params);
FB.ui(params, function(obj) { console.log(obj);});
}
</script>
Thank you,
raj
You are missing semicolon in this line :
window.location = "test.html"
This question was posted a while ago but I would like to point out something. FB.login function opens a popup dialog asking if the user would like to log in to your app using Facebook. It is generally recommended that it be run after clicking a button as most browsers would block popup dialogs when a page loads. If the user had previously authorized your app then the popup dialog redirects back to your app and closes the dialog box (assuming your app is a website).
If what you intended to do was to check whether a user is logged in to your app upon page load, then it's recommended that you instead use FB.getLoginStatus method like so
function checkLoginState() {
FB.getLoginStatus(function(response) {
// Check response.status to see if user is logged in
alert(response.status);
});
}
Refer to this extensive documentation on facebook
Related
Goal : Connecting an application with existing Facebook page.
Why ? I want to allow user to use their page as bot. Facebook app is a bot.
Reason : User wants a bot for Facebook page but does not allow admin permissions.
What I've tried :
Get all users pages :
if ( typeof (response.authResponse) !== 'undefined')
{
token = response.authResponse.accessToken;
$.ajax({
url: "api/FB/GetCode?token=" + token,
}).done(function (data) {
var mySelect = $('.dropdown');
mySelect.empty();
$.each(data.accounts.data, function (val, text) {
mySelect.append(
$('<option></option>').val(text.access_token).html(text.name)
);
});
mySelect.show();
$('.connectWithBot').show();
});
} else {
//do the login logic
}
Then when user has chosen page :
FB.api(
'pageId/subscribed_apps?access_token=' +
$('.dropdown').find(":selected").val(),
'post',
function (response) {
console.log(response);
if (response && !response.error) {
console.log(response);
}
});
So when one page instance is connected with one application, this not gonna work anymore. Its okey that way.
Is it possible to get this work ? Or maybe you guys have a better idea ?
Last year i build a form for one of our costumers, when visitors submitted the form they
got a message on the same page. But now he asks me if it is possible to
make a succes page if the form is filled in correctly.
I can't make it work. It's a bit out of my league.
So i hope anyone of you can help me out!
$(document).ready(function() {
$("#ajax-contact-form").submit(function() {
$('#load').append('<center><img src="ajax-loader.gif" alt="Currently Loading" id="loading" /></center>');
var fem = $(this).serialize(),
note = $('#note');
$.ajax({
type: "POST",
url: "contact/contact2.php",
data: fem,
success: function(msg) {
if ( note.height() ) {
note.slideUp(500, function() { $(this).hide(); });
}
else note.hide();
$('#loading').fadeOut(300, function() {
$(this).remove();
// Message Sent? Show the 'Thank You' message and hide the form
result = (msg === 'OK') ? '<div class="success">Uw bericht is verzonden, we nemen z.s.m. contact met u op!</div>' : msg;
var i = setInterval(function() {
if ( !note.is(':visible') ) {
note.html(result).slideDown(500);
clearInterval(i);
}
}, 40);
}); // end loading image fadeOut
}
});
return false;
});
<form id="ajax-contact-form" target="_blank" method="post" action="javascript:alert('success!');" >
Instead of displaying the "success" message, redirect to a new page:
window.location = successPageUrl;
Just redirect to success page after ajax success.
I am attempting to implement an asynchronous loading Facebook log in button, but the button disappears after 45 seconds (in Google Chrome only) and this error message is logged in the error console: "FB:login_button failed to re-size in 45s". How do I solve this problem?
Here are the errors that are logged in the error console:
Uncaught TypeError: Cannot read property 'style' of undefined connect.facebook.net.js:123
v connect.facebook.net.js:123
o.extend.constructor.ha connect.facebook.net.js:123
g.inform connect.facebook.net.js:40
(anonymous function) connect.facebook.net.js:123
ka connect.facebook.net.js:67
h.setWrapper.j connect.facebook.net.js:62
r.register.init.s connect.facebook.net.js:66
h.setWrapper.j connect.facebook.net.js:62
fb:login_button failed to resize in 45s
Here is the HTML:
<div class="fb-login-button" data-show-faces="false" size="xlarge" data-width="300" data-max-rows="1"></div>
Here is the Javascript:
ADS.addEvent(window, "load", function(){
if(!ADS.$('fb_root')){
var div = document.createElement('div');
div.id = "fb-root";
document.body.appendChild(div);
var script = document.createElement("script");
script.src = "dom/connect.facebook.net.js";
var script2 = document.createElement("script");
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);
window.fbAsyncInit = function () {
FB.init({
appId: "HIDDEN",
channelUrl: "http://mywebsite.com/channel.php",
status: true,
cookie: true,
xfbml: true
});
// Gets status when the user first lands
// on site
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//window.location="http://mywebsite.com";
} else if (response.status === 'not_authorized') {
// Do nothing, let the user view the welcome page
//FB.login();
} else {
// this causes a login dialog to
// pop up automagically once the user
// lands on the site and is not logged in
// or authorized
//FB.login();
}
});
function login() {
FB.login(function(response) {
if (response.authResponse) {
// connected
// using event subscribe to send user to right page, instead of this
// which does not redirect the user once the login is complete
//window.location="http://mywebsite.com/home.php?show=follow";
} else {
// cancelled
//alert(response.authResponse);
}
});
}
FB.Event.subscribe("auth.login", function () {
// Redirect's the user once the login is complete
window.location="http://mywebsite.com";
})
}
}
});
I’m creating a custom share to facebook functionality, which has been more complicated than I originally thought.
I’ve had to create a facebook app and then use It’s ID to get it going.
If you try to share the page on facebook, it gets you login to facebook(if not logged in), then it requests access to your profile(only on your first share), and then proceeds to share dialogue to let you share it.
However I’ve noticed that other sites including youtube and BBC, that they don’t request access to share on facebook, It will take you straight to the share dialogue instead.
Is there a way to achieve this?
Code using is below:
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : '*APP_ID*', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
link : '*LINK*'
});
$('.share-print .facebook > a').click(function(e){
e.preventDefault();
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
facebookSend();
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
FB.login(function(response) {
if (response.authResponse) {
console.log('Logged in');
facebookSend();
} else {
console.log('Not logged in');
}
});
} else {
// the user isn't logged in to Facebook.
FB.login(function(response) {
if (response.authResponse) {
console.log('Logged in');
facebookSend();
} else {
console.log('Not logged in');
}
});
}
});
});
var facebookSend = function() {
console.log('facebookSend started');
FB.ui({
method: 'feed',
display: 'iframe',
link: '*PAGE_LINK*'
});
}
</script>
I am using FB.getLoginStatus() and FB.Login() to log the user into my website using facebook. I first check for the status on page load using FB.getLoginStatus() and save the state in a hidden variable. When the user clicks on my facebook login button, I first check the value in the hidden variable and call FB.Login() only if FB.getLoginStatus() is not connected. If FB.getLoginStatus() returns 'Connected', then I just log the user into my website without FB.Login().
My scenario with issue
*user logs into my accont using facebook
*user logs out of my website
*my website is open in the logged out state
*in another tab, the current facebook user logs out of facebook and a new user logs into facebook
*user comes back to my website and clicks on facebook login button without refreshing the page
*the old facebook user (not the one currently logged into facebook) is logged into my account
How can I identify the most current user in facebook when user clicks the facebook login button?
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div id="fb-root">
</div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
// initialize the library with your Facebook API key
var AppID = '<%=AppID%>';
window.fbAsyncInit = function() {
FB.init({
appId: AppID,
status: true,
cookie: true,
xfbml: true,
channelUrl: 'http://<%=Request.ServerVariables("HTTP_HOST")%>/channel.html'
});
FB.Event.subscribe('auth.login', function(response) {
//alert('logged in');
});
FB.Event.subscribe('auth.logout', function(response) {
//alert('logged out');
});
FB.getLoginStatus(function(response) {
if (response.status === "connected") {
var uid = response.authResponse.userID;
document.getElementById('hdnFBConnected').value = uid;
}
else if (response.status === "not_authorized") {
//alert("Not authorized");
document.getElementById('hdnFBConnected').value = '';
}
else {
//alert("user not logged in to facebook");
document.getElementById('hdnFBConnected').value = '';
}
});
};
</script>
<img src="<%=global_language & "/images/FacebookSmall.gif"%>" />
<script type="text/javascript" language="javascript">
function WindowOpen() {
if (document.getElementById('hdnFBConnected').value != '') //user is connected
{
FB.api('/me', { fields: 'first_name, last_name, locale, email' }, function(result) {
var uid = document.getElementById('hdnFBConnected').value;
//log the user into my site
})
}
else { //user is not connected, so calling FB.Login()
FB.login(function(response) {
if (response.authResponse) {
var access_token = response.authResponse.accessToken;
FB.api('/me', { fields: 'first_name, last_name, locale, email' }, function(result) {
var uid = response.authResponse.userID;
var globalLang = '<%=global_language%>';
//log the user into my site })
}
else {
//alert('User cancelled login or did not fully authorize.');
}
}, { scope: 'email' }
);
}
}
</script>
</body>
What you're describing is normal behavior. The JS SDK is sending the old user's signed_request object which allows the new user to access her account. Since this concerns you, include a logout button on your app's page and let the user know that it's important she clicks that button when she's done using your app. The logout button should call FB.logout like so:
FB.logout(function(response) {
// user is now logged out
});
For extra security, you can create an activity timer that prompts the user to click a button after X minutes of inactivity. If the user doesn't click within, say 1 minute, she is logged out automatically. This is how most banking sites deal with session security.