Getting facebook likes count via javascript SDK - javascript

I have the following script:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'app_id_of_one_of_my_apps',
xfbml : true,
version : 'v2.7'
});
FB.api("/{numerical_profile_id}/likes",
function (response) {
console.log(response);
if (response && !response.error) {
/* handle the result */
}
});
};
(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/pl_PL/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
All I get is error An access token is required to request this resource
How do I securely get Facebook fanpage likes count via javascript? Or do I need to make a PHP script that will do it for me?

This is the API to get the fan count:
/{page-id}?fields=fan_count
...or with the JavaScript SDK:
FB.api('/{page-id}', {fields: 'fan_count'}, (response) => {
console.log(response);
});
You can use an App Token if the page is not restricted by age or location, but you MUST use the Token server side. Tokens are always meant to be kept secret. No login is needed for the App Token, it is just a combination of App ID and App Secret (ID|Secret) and it is permanent.
More information about Tokens:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
Side note: You should do that API call server side anyway and cache the result in your database, or you will definitely hit the API limit if you get a lot of users/hits.

Related

How to get response from facebook share button?

This is facebook share button code from facebook
<div id="fb-root"></div>
<script>(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#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<!-- Your share button code -->
<div class="fb-share-button"
data-href="http://www.your-domain.com/your-page.html"
data-layout="button_count">
</div>
How can I get response of success or error from this?
I tried some examples but didn't got response after sharing via code.
Share button works and it also sharing the post.
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '1743496239724', // App ID from the App Dashboard
//channelUrl : 'http://exampb.com/plugins/', // Channel File for x-domain communication
status : true, // check the login status upon init?
cookie : true, // set sessions cookies to allow your server to access the session?
xfbml : true // parse XFBML tags on this page?
});
// Additional initialization code such as adding Event Listeners goes here
FB.ui(
{
method: 'feed',
},
function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
};
// 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));
I tried this but its conflicting. With that share button obtained from FB.
You can use the Share Dialog, but it only responds with a proper callback if you authorize the User with the publish_actions permission: https://developers.facebook.com/docs/sharing/reference/share-dialog

Get most recent post from Facebook page, and display on website using new Graph API JavaScript only

I'm building a website for a business. The business currently has a Facebook page. On the website i'm creating, i need to display the most recent Facebook post.
A Google search led me to a depreciated method, and Facebook says now to use the new Graph API, but i'm starting from no Facebook API experience so found it overwhelming and could use some help.
Here's where i am.
I'm doing this as a single page site with no server side language, so am only using JavaScript. So far I've got the FB JS SDK script after my body tag, and a app-id setup for my page.
<script>
window.fbAsyncInit = function () {
FB.init({
appId: 'your-app-id', // except real id
xfbml: true,
version: 'v2.4'
});
};
(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>
I have linked my FB app with my FB page. Now i need to display the most recent post on my website.
FB.api(
"/{page-id}/feed",
function (response) {
if (response && !response.error) {
/* handle the result */
}
}
);
Source: https://developers.facebook.com/docs/graph-api/reference/v2.4/page/feed
You could just use the following API call to get only one entry:
/{page-id}/feed?limit=1
window.fbAsyncInit = function() {
FB.init({
appId : 'app id here',
autoLogAppEvents : true,
xfbml : true,
version : 'v3.2'
});
//For getting posts from wall,
FB.api(
'/me',
{access_token:'Access token here',
fields:"id,name,posts{attachments}"},
function(response) {
console.log(response)
}
);
//for getting posts from page we manage
FB.api(
"/page_id/feed",
{access_token:'access token',
fields:"attachments{url,media,description,title,type},created_time,description,message,updated_time"},
function (response) {
console.log(response)
if (response && !response.error) {
/* handle the result */
}
}
);
};
(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 = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

An active access token must be used to query information about the current user

I'm trying to output my Facebook feed to a div element.
Using this code:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'APP ID HERE',
xfbml : true,
version : 'v2.1'
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
console.log('Logged in.');
}
else {
console.log('initiate FB login...');
FB.login();
}
});
FB.api('/me/feed',function(response){
var idDiv=document.getElementById('result');
idDiv.textContent=JSON.stringify(response);
});
};
(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";
console.log(js.length);
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<div id='result'></div>
I get "logged in" displayed on the console, so I know that FB.getLoginStatus() has returned connected.
The div element gets populated with the following error:
{"error":{"message":"An active access token must be used to query information
about the current user.","type":"OAuthException","code":2500}}
If FB.getLoginStatus() returned connected, shouldn't there be an active access token?
You probably don't have the access token at the time the request to 'me/feed' is sent.
getLoginStatus does not only check if the user is authorized, it also refreshes the user session. that´s why it is important to do api calls after it is "connected".
Try putting the call to FB.api inside getLoginStatus.
This question is similar to the problem you're having:Facebook javascript sdk An active access token must be used to query information about the current user

Parse.com Facebook API logIn() method. Callback never gets called

When my click handler calls logIn() function on a client, I see a FB popup and a record being created in User collection, but callback methods are never called. Instead, I see the following in JS console
Uncaught TypeError: Cannot read property 'getTime' of null parse-1.2.18.min.js:3
Here is the code on my page
Setting up FB API
<script>
window.fbAsyncInit = function() {
Parse.FacebookUtils.init({
appId : 757503280935086,
xfbml : true,
version : 'v2.0'
});
};
(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>
Calling login method
$scope.signupFB = function() {
Parse.FacebookUtils.logIn(null, {
success: function(user) {
//never get here
$timeout(function() {
$rootScope.theUser = user;
$location.path("/properties");
});
},
error: function(user, error) {
$scope.error = "User cancelled the Facebook login or did not fully authorize.";
}
});
}
The FB app has a website "Platform" enabled.
Next time I tried I saw
Uncaught Error: Setting authResponse is not supported
in JS console.
NOTE: This fix is no longer required (and instead will actually break it) as Facebook fixed the API call to return the date in the old string format.
Facebook added v2.0 of the API recently, unfortunately they broke Parse. In particular Parse uses a very strict rule for reading the date from the Facebook response.
A workaround is to download the parse-1.2.18.js file, and update the Parse._parseDate function, then load that JS file into your site and change your pages to use that instead of the current version:
Parse._parseDate = function(iso8601) {
var regexp = new RegExp(
"^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})" + "T" +
"([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})" +
"(.([0-9]+))?" + "Z$");
Update it to this:
Parse._parseDate = function(iso8601) {
var iso8601 = iso8601.split(“+”)[0] + “Z”;
var regexp = new RegExp(
"^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})" + "T" +
"([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})" +
"(.([0-9]+))?" + "Z$");
Basically it is just stripping off any “+00:00” from the end and adding the “Z” back on so that it works again.
You could make it more robust (in case Facebook revert to the old date format) by using this instead:
var iso8601 = iso8601.split(“+”)[0].split(“Z”)[0] + “Z”;
That way if the “Z” gets put back on we grab everything before it and don’t break.
There’s a bug logged in the Facebook bug tracker that also shows an updated regexp that will work with both, I don’t have the link handy though.
UPDATE: Also ensure you're using the right version of the API.
If you follow the instructions on Facebook now, they want you to have a section like this:
(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'));
Note that if you are using the sdk.js you'll need to pass a version parameter to the init call, which for Parse will end up looking like this:
window.fbAsyncInit = function() {
Parse.FacebookUtils.init({
appId : yourAppId,
xfbml : true,
version : 'v1.0'
});
};
We are explicitly setting the version to 1.0 until such time as Parse update their code to handle 2.0.
The problem comes from using the v2 facebook api.
Switching to the old version with Timothy's fix works.
window.fbAsyncInit = function() {
Parse.FacebookUtils.init({
appId : '' // Facebook App ID
});
};
(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'));
Notice including all.js not sdk.js

Facebook Javascript SDK Not Loading

I have just started working with the Facebook SDK and I am trying to use a script which grabs a user's name and friend's list. This is the initialization code I am working with:
window.fbAsyncInit = function()
{
console.log("initialising");
FB.init(
{
appId : 'APPID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : false // dont parse XFBML
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
console.log("RESPONSE IS CONNECTED!");
} else if (response.status === 'not_authorized') {
console.log("NOT AUTHORIZED");
} else {
console.log("NOT LOGGED IN");
FB.login();
}
});
};
(function(d, s, id){
console.log("Loading SDK!");
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'));
I have an fb-root element at the top of the document, outside of the script tags.
About half of the time, the SDK loads fine and I see the initialising and connected messages in the console. However, the other half of the time, I only see the "Loading SDK" message and nothing else, which I assume means that the SDK isn't loading correctly for whatever reason. I have also noticed that it loads on navigation to the page, but rarely on refresh.
My question is: what is causing the SDK to not load some of the time and how can I solve the issue?
According to the latest documentation from Facebook regarding the use of the Facebook JavaScript SDK, the method to include the SDK asynchronously has been updated:
(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));
It's not immediately obvious to me why this would be more reliable as compared to your approach but I can say this is what I use on my site and I have not experienced any intermittent issues,

Categories