I'm trying to load some posts asynchronously via the javascript SDK from facebook. I'm loading the javascript files at the bottom of the page:
<html>
<head>.....</head>
<body>
.....
.....
.....
<div id="fb-root"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="/res/jquery.stp.js" charset="utf-8"></script>
</body></html>
In jquery.stp.js I'm loading these things in this order:
- the javascript sdk
- some jquery-things
- a function loadFBPosts()
- fb.init()
The file:
var isLoaded = false;
(function(d, debug){
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" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);
}(document, /*debug*/ false));
$(function(){
//some jquery event things
})
function loadFBPosts(fbPageId) {
// Facebook call
if(isLoaded) {
//do some things with the FB.api()
//and catch errors...
}else{
//api not loaded...
}
}
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : 'xxxxx',
channelUrl : '//lab.example.com/channel.php',
status : true,
cookie : true,
xfbml : true
});
isLoaded = true;
laadFBPosts(); // here after FB.init is initialized call the function.
};
Questions
Now something odd happens. If I run this page an error pops up: "An access token is required to request this resource" with error-code 104.
But if I click a link on the page <a href='javascript:loadFBPosts()'>click</a> then the function gets execute like it should.
How is this possible? The resources I try to get with the FB.api() are from public facebook pages. eg FB.api('/218818688131271/posts?limit=5') so I shouldn't need an access token. Right?
If I do need an acces token: how do I obtain one if I don't want to bother every visitor with a login screen; because it's just a displaying of public info....
The only thing I want to do is to display the last 5 posts off my page and the upcoming events.
Related
I am using the offcial sample from facebook: it works fine, except I cannot retrieve the birthday and location.
<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
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 : 'xxx',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.2' // use version 2.2
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
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'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me?fields=id,first_name,last_name,gender,location,email,birthday', {fields: 'name, email,gender,first_name,last_name,location,birthday' }, function(response) {
console.log(response);
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
});
}
</script>
<!--
Below we include the Login Button social plugin. This button uses
the JavaScript SDK to present a graphical Login button that triggers
the FB.login() function when clicked.
-->
<fb:login-button show-faces="false" scope="public_profile,email,user_birthday,user_location" size="medium" onlogin="checkLoginState();">Connect with facebook</fb:login-button>
<div id="status">
</div>
</body>
</html>
This works fine but no borthday nor location in response.
I spent a lot of time and it looks that nowdays to retrieve these informations I need to nowdays to REVIEW the application before accessing these data
https://developers.facebook.com/docs/facebook-login/review/what-is-login-review
Is this correct: do I need to submit the application for review or is it something wrong I am doing ?
Yes, it's true, and it's all in the docs:
https://developers.facebook.com/docs/facebook-login/review
https://developers.facebook.com/docs/apps/review
But, if you're using the an admin/tester/developer of the said app, you are able to give and test these permission with your app. Only if third parties will need to access the app, you'll need to pass Login Review.
First, a facebook user is logged client-side with using Facebook JS SDK.
FB.init() is called with the following parameters:
{
version : 'v2.0',
appId: '...',
status : true,
cookie : true,
xfbml : false
}
Then, in PHP, a session is created:
$session = (new FacebookJavaScriptLoginHelper())->getSession();
Once FB API calls have been made from PHP, I still can continue calling FB API from withing js.
But as soon as my page sends a new command to the server instructing it to make an FB API call, it doesn't work the second time, and the FB API says:
An access token is required to request this resource.
Obviously, this is called one more time and after that it stops working:
$session = (new FacebookJavaScriptLoginHelper())->getSession();
If the user updates the page in his browser, the next call from the server will work again. What I want instead is to keep querying FB API from both the server and the browser simultaneously without reloading the page.
It is out of date, but maybe will help someone
<?php
//some code here - requires and uses
FacebookSession::setDefaultApplication($SETTINGS['fbappid'], $SETTINGS['fbsecret']);
$helper = new FacebookJavaScriptLoginHelper();
$session;
try {
$session = $helper->getSession();
} catch(FacebookRequestException $ex) {
//
} catch(\Exception $ex) {
//
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $SETTINGS['fbappid'] ?>',
xfbml : true,
version : 'v2.0',
status : true,
cookie : true
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
FB.login(function () {
FB.api('/me', {
fields: 'id'
}, function (response) {
console.log(response);
});
}, {
scope: 'publish_actions'
});
} else if (response.status === 'not_authorized') {
} else {
}
});
};
(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>
<div id="fb-root"></div>
<?php
//here url to go to my app
echo "<a href='...'>Sign in to Facebook application</a>";
if ($session) {
echo "<br/>logged in";
}
?>
</body>
</html>
Note that login comes after second access to page if cookies were not set. So ajax request is needed to check properly.
I have a Facebook page. I want to know if a person has clicked on like button or not and do something in subscribe.event 'create-edge' callback.
This works fine if a person is already logged into Facebook. The 'create-edge' event is getting fired. However, if a person is not logged in, this event is not getting fired.
I don't have any appId, so I'm sending it nothing.
Code for your reference:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://ogp.me/ns/fb#" >
<head>
<meta charset="utf-8">
<title>Facebook Like Button</title>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '', // App ID
channelURL : '', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : false, // enable OAuth 2.0
xfbml : true // parse XFBML
});
FB.Event.subscribe('edge.create', function(response) {
alert("say something");
//my code
});
FB.Event.subscribe('auth.login', function(response) {
alert('The status of the session is: ' + response.status);
});
};
// 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>
<fb:like href="http://www.facebook.com/My_Page" send="false" layout="button_count" width="450" show_faces="false"></fb:like>
</body>
</html>
And also i am getting this error:
FB.getLoginStatus() called before calling FB.init().
Seems like I am getting it because I don't have any appId to send in FB.init.
What is the cause of this?
This happens if the user has already liked your page, and is not logged in. To fix this, I had to put FB.init() in a loop.. like this:
setInterval(function()
{
FB.init({
appId : 'app_id'
channelUrl : 'channel_url'
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : false // parse XFBML
});
}, 5000);
SO I am trying to have my web site publish info to a user's facebook page. Where I am now is that I placed the following code (as instructed by another stackoverflow contributor), which is getting executed however the alert with "error occurred" comes up. Do I need to request the publish_stream permission as well? If so, I cannot figure out how to add that to my code. Sorry, I'm not much of a scripter and I have very limited knowledge on doing any integration into facebook. My ultimate goal is to be able to post information to a users facebook page on their behalf (this won't be done without their permission). Any help would be much appreciated:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXXXXXXXXXXXX', // App ID
channelUrl : '//www.XXXXXXXXXXXXXX.com/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
oauth : true
});
});
// Additional initialization code here
};
// 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>
<SCRIPT language="JavaScript">
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
</SCRIPT>
<SCRIPT language="JavaScript">
var body = 'Reading JS SDK documentation';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
})
</SCRIPT>
Why don't you expand the error handling a little bit?
alert("Error occured: " + response.error.message);
And did you check the console log for errors? Maybe authentication didn't work.
Is something like this possible?
I have a client launching an online magazine for his business. He wants to add a facebook like button (for the magazine fanpage) on his current corporate site and ask users to 'like it' in order to be taken to the magazine website. Can it be done? Are there drawbacks to this approach? For example, the same user will have to 'like it' every time they want to access the magazine site?
Thank you for any suggestion, I'm pretty new to facebook.
You can redirect a user on clicking a like button using the Javascript SDK and FB.Event.Subscribe
FB.Event.subscribe('edge.create', function(response) {
window.parent.location = 'http://www.google.com';
});
edge.create is called when ever a user likes something on the page
response is the url that has just been liked.
If there are multiple like buttons on the page you could use an if statement with the response to make sure the page only redirects for a particular like button
Here's the full javascript code and a like button
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
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
});
FB.Event.subscribe('edge.create', function(response) {
window.parent.location = 'http://www.google.com';
});
};
// 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/<?php if(isset($fb_user['locale'])){echo $fb_user['locale'];}else{echo'en_US';}?>/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<fb:like href="http://www.google.com" send="false" width="450" show_faces="true"></fb:like>