I'm trying to reveal content on my website only to people who like my facebook page. I've tried severall tutorials but none of them work. The closest I got was following this:
http://www.dejanlevec.com/2011/05/11/how-to-display-certain-page-content-only-to-users-who-have-liked-our-page-on-facebook/
I can get it to work if I first dislike the page and then like it on the facebook_test.php . Thus it doesn't detect if I already like the page.
I have done this with javascript before using FB.Event.subscribe and edge.create as described below:
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: 'APP_ID_HERE', status: true, cookie: true, xfbml: true});
FB.Event.subscribe('edge.create',
function (response) {
window.location = "http://redirectexamplehere.com";
});
FB.Event.subscribe('edge.create',
function (response) {
window.location = "http://redirectexamplehere.com";
});
};
(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>
This way a user will be redirected to wherever you specify upon them liking the page. Remember to load the SDK first or it won't work.
Detecting if a user likes you on a website is a bit trickier than in a Facebook page. You'll need to setup a Facebook application and use that on your website and have the user authenticate using the app in addition to liking your page. Once you have that connection with the user you can test to see if they are logged in and have liked your page. At that point you can display different types of content.
The extra step of having to authenticate the user is probably why you don't see this implemented on too many websites.
Related
Facebook's Javascript SDK has a method called getLoginStatus that stalls (and never fires the callback passed into it) while an image request on the page also stalls (i.e. the browser doesn't receive a 200 or 404 for a very long time.)
If you wait an extremely long time and the browser (?) finally closes out the attempt to fetch the image, the SDK continues on its merry way.
What might be going on, and is there a way to prevent it? It's awfully inconvenient when a user can't sign in or sign up just because of an image request.
Blocking (HTML):
<img src="..." />
Non-Blocking (with CSS):
#someDiv {
background-image: url(...) no-repeat;
width: xxx;
height: xxx;
}
Non-Blocking (with JS):
var img = new Image();
img.onload = function () {
document.getElementById('someDiv').appendChild(img);
};
img.src = "...";
Try with solution number 2 or 3 - there are also many preloader plugins for JavaScripts making it easier for you to load a lot of images asynchronously, for example: http://thinkpixellab.com/pxloader/
Another solution would be to load smaller images first and load the hires ones asynchronously.
When you use the initialization code from the Facebook SDK website, by default it wants to wait for the page to be fully loaded be for running certain events, like the fbAsyncInit function.
I'm not sure of an "officially supported" way to bypass this, but you could load the Javascript source yourself and call the routines outright (i.e. not in the async wrapper).
This is a barebones example that stalled like you mentioned using the Facebook SDK initialization procedure but works fine with this workaround.
<html>
<head>
<title>This is a test</title>
<script src="http://connect.facebook.net/fr_FR/sdk.js"></script>
<script language="javascript">
<!--
var loggedIn = false;
var authenticated = false;
FB.init({
appId : '{your app ID here}',
xfbml : true,
version : 'v2.0'
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
loggedIn = true;
authenticated = true;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
loggedIn = true;
} else {
// the user isn't logged in to Facebook.
}
});
function testLogin()
{
alert("Logged in: " + loggedIn + "\nAuthenticated: " + authenticated);
}
// -->
</script>
</head>
<body>
Testing!
<button onclick="testLogin()">Test login?</button>
<img src="http://deelay.me/5000/ http://example.com/image.gif">
</body>
</html>
I'm not sure how this will affect integration with your site, but I can't imagine it would be a problem. If anything I suppose it's worth a shot!
Do you have any adblockers setup? I had a similar problem with a different API and Adblock Pro was causing some issues.
I'm wanting to implement the "Login With Facebook" that's common on websites but I'm having trouble grasping the whole concept and if anyone could assist me with this I'd be most appreciative.
I've been reading the documentation under this link https://developers.facebook.com/docs/facebook-login/ for days but I still don't "Get It".
Let's start with...
In the documentation, it says the JS SDK is easiest to use (for whom I dont know) but I'm thinking the NON JS version would be better and faster (and easier for me to grasp) but I don't know what to do. I'm "Stuck"
My main problem is I don't understand how I am suppossed to be able to insert an Auto Incrementing ID along with the person's first and last name into my DB. There's NOTHING or NOWHERE in the Facebook code where I could specify a DB, Table or Column so how is this data suppossed to get into my DB to log the user in??
I have a classifieds on my site of which I'm attempting to create a FB login for but as I said above, I'm stuck and could use help as I have only an intermediate level of knowledge regarding PHP and MySql
Like discussed in comments, here's example using JS SDK
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <!-- jQuery library, makes things easier. -->
<title>FB example</title>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : YOUR_APP_ID, // App ID from the app dashboard
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
};
// 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/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
/*
This function gets information about user and alrets user's name.
*/
function getUserInfo() {
FB.api('/me', function(response) {
$.ajax({
url: "ajax.php", //url to send ajax request to
data: {
json: response, // Key => value pairs of items to send
},
success: function(ajaxResponse) { // upon successful request
alert(ajaxResponse); //Alert whatever response we got.
}
})
})
}
/*
This function gets the login status of user
*/
function getLoginStatus() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') { //User is connected to Facebook and authorized your app
getUserInfo();
} else if (response.status === 'not_authorized') { //User is connected to Facebook, but hasn't authorized your app
login();
} else { //User is not connected to Facebook
login();
}
});
}
/*
Function promts user to log in and asks for permissions
*/
function login() {
FB.login(function(response) {
if (response.authResponse) {
getUserInfo();
} else {
alert('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'}); // Comma separated permissions
}
</script>
<a href="javascript:getLoginStatus()"/>Login</a>
</body>
</html>
This is very simple example. On the page you will see link "Login". Upon pressing it you'll be either asked to login (if you're not logged into Facebook, or you haven't authorized app yet), or it will show popup with your name. Most of the code has been taken from JavaScript SDK documentation
EDIT:
To add user's data to your database, i would suggest making AJAX call from the getUserInfo() function. Replace alert part with ajax call to certain php file, which you will create and pass it the data from response variable (which contains data about user, like response.name and response.email). In the php file itself insert the information you got into database.
ANOTHER EDIT:
I've updated the code once again, namely i added jQuery library (easier for me to make ajax calls in it, although it's not much different from plain JS).
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
And updated getUserInfo() function to make ajax request to ajax.php.
In ajax.php i've made only one line:
print_r($_REQUEST['json']);
This will simply print out whatever data was send via ajax, and you will see it in popup. Next step would be checking out what information you get, and take whatever you need (it's $_REQUEST['json'] is simple array), and insert it into db.
edit: explanation:
When Facebook login button should appear and when not? On facebook tutorial page it is not accurately explained. There is written: "If the user is already logged in, no login button is shown". But for me, it is true only when user is logged in both in facebook profile and my facebook application connected to my website! It is not true, that button is removed when you are logged in just on facebook profile, as it is mentioned on the facebook tutorial. Am I right? –
could anybodey help?
thanks
tomas
//old message
I have Facebook login button on my website. Sometime visitors are logged in facebook byt are not logged into my website (my application on fb). In this case, Login buton is displayed but does nothing. As I know, Login button should not only log in facebook but also login to my application.
It works OK when user is logged out both from facebook and application (website) before clicked. But what if user is logged in just to facebook? Then my button does nothing.
You can render a button for connect session and another for those with out session.
Sample Usage: Using getLoginStatus() to determane if user is connected to app, and XFBML.parse to render the button. https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
I opted out of using channelURL but you can create your own and read about here. https://developers.facebook.com/docs/reference/javascript/
if user is connected and logged in, logout button appears.
if user is not connect but logged into facebook login button appears.
if no session or login login button appears.
Async JavaScript SDK
<div id="fb-root"></div>
<!-- build1 is where we render our button based on connected status. -->
<div id="build1"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YourAppId',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
//channelUrl : 'http://WWW.MYDOMAIN.COM/channel.html', // channel.html file
oauth : true // enable OAuth 2.0
});
if (window!=window.top) {
FB.Canvas.setAutoResize();
}
FB.getLoginStatus(function(response) {
if (response.authResponse) {
// logged in and connected user, someone you know
// render button
Cbuild1 = document.getElementById('build1');
Cbuild1.innerHTML = "";
Cbuild1.innerHTML = "<fb:login-button autologoutlink=\"true\"></fb:login-button>";
FB.XFBML.parse(Cbuild1);
} else {
// no user session available, someone you dont know
// render button
Cbuild1 = document.getElementById('build1');
Cbuild1.innerHTML = "";
Cbuild1.innerHTML = "<fb:login-button></fb:login-button>";
FB.XFBML.parse(Cbuild1);
}
});
};
(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>
functionality of loginStatus tested here https://shawnsspace.com/fb.test.connect.loginbutton.php
I have the same problem. I tried Shawn E Carter 's solution and still no improvements.
But i observed the new parameter for oauth in the FB.init call. If i set it on true it works as expected.
I'm totally confused about Facebook's dialog feed, sharer and like buttons (I'm a noob to Facebook and its jargon)
On my website, I would like the following
to have a button at the top of the page where people can share my site to their wall
to have a button on the the page where users can share their main homepage on my site to their wall
to have a button where users can share individual items of theirs (events) to their wall
I've read the sharer button is being phased out in preference to the Like button but I see a problem with the Like button. I think something can only be liked once. A user's event might want to be shared several times (to remind their Fb users of the event)
I've seen the BBC use the dialog feed button to post items to a wall and that looks okay but I couldn't get the popup to work.
my requirements are to have different links for each of the three scenarios I've mentioned, with a different description for each scenario but sharing my site's logo.
I've read so much that I'm now totally confused plus all the APIs that Fb has. It's just crazy (or that's how it seems to me)
If someone could help clear the fog with sound recommendations and some sample code for each button, I would be very grateful.
Thank you.
.
For what your talking about you would want to use the feed dialog. It's flexible enough that you just need to setup your links and pass in some variables. I don't see the feed dialog being phased out as you mentioned they serve different purposes. I think they push the like as it's easier to use and not as likely to be abused.
You'll need to register an application and make sure to initialize the Facebook javascript SDK before you call the below function. If you're having issues with your popup it's probably due to the fact your FB init process is having issues. I've added a second function I use to init Facebook. Both functions use jQuery so you might have to modify if you don't use it.
You can create a pretty generic function like this:
$.shareMe = function(myName, myLink, myPicture, myCaption ) {
FB.ui(
{
method: 'feed',
name: myName,
link: myLink,
picture: myPicture,
caption: myCaption
},
function(response) {
if (response && response.post_id) {
alert('Thanks for Sharing.');
} else {
alert('Post was not published.');
}
}
);
}
and for Facebook initialization:
$.initFacebook = function(options){
$('#fb-root').remove();
$('body').append('<div id="fb-root"></div>');
var settings = {
'appId' : null,
'callback' : null,
'channelUrl' : null,
'status' : true,
'cookie' : true,
'xfbml' : true
};
if ( options ) {
$.extend( settings, options );
}
if( typeof( xc_app_id ) == 'undefined' ) { window.xc_app_id = settings.appId; }
window.fbAsyncInit = function() {
if(settings.channelUrl==null) {
FB.init({appId: settings.appId, status: settings.status, cookie: settings.cookie, xfbml: settings.xfbml, oauth: true, authResponse: true });
} else {
settings.channelUrl=location.protocol+'//'+settings.channelUrl;
FB.init({appId: settings.appId, status: settings.status, cookie: settings.cookie, xfbml: settings.xfbml, oauth: true, authResponse: true, channelUrl: settings.channelUrl });
}
if(typeof settings.callback == 'function'){ settings.callback.call(this); }
};
(function() {
var e = document.createElement('script');
e.async = true;
e.src = '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
}
and to call it you just use $.initFacebook({appId,'yourAppId'}); There are other options there you can lookup in the docs if you need them.
in my website, for each blog entry I have a facebook like button. So on the index, there is multiple(more than 10 at the moment) like buttons.
These like buttons make my page a bit cumbersome to use. The total page time becomes several seconds and it's laggy/jumpy while loading(even though all the content is loaded) while it's loading. Is there anyway to fix this other than not showing the like button on the index? (a single like button on a page produces negligible lag)
For reference, my website is at http://lastyearswishes.com In firebug, you can see that the page load time is 20 seconds, of which about 200 milliseconds is tied back to my actual website. Each facebook like button appears to do three separate non-cacheable, unique requests.
Afterthought: Now (nearly 2 years later) I decided to give up on facebook. Even with asynchronous code it still enduced a noticable delay in page rendering time. It also uses some stange javascript that screws up my layout. When dropping in twitter buttons, my layout looked immediately the way it should (something with alignment and float that facebook did. I could never use margin or anything to get facebook to line up like I wanted)
Facebook Developers provides the javascript to create an asynchronous Like button
found here: Loading the SDK Asynchronously
c/p'd here:
<div id="fb-root"></div>
<script>
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>
Updated:
Try just this portion (and add #xfbml=1 at the end of the URL, should be the same result on your site but async loading):
<div id="fb-root"></div>
<script>
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js#xfbml=1';
document.getElementById('fb-root').appendChild(e);
}());
</script>
Put this script at the bottom of your page