Fb.api post to user wall only on login - javascript

I would like to use fb.api to post on logged user, but just once. If I put this
var params = {};
params['message'] = 'gegeegeggegall! Check out www.facebook.com/trashcandyrock for more info.';
params['name'] = 'gegeggeeg - gegegege';
params['description'] = 'Check out Tegegegeg! Win merch by playing and reccomending to your friends.';
params['link'] = 'http://www.bblblba.com';
params['picture'] = 'http://summer-mourning.zoocha.com/uploads/thumb.png';
params['caption'] = 'Tgegegegeeg';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Published to stream - you might want to delete it now!');
}
});
It posts to users wall everytime he refreshes the site?
What to do?

What is triggering the FB.api call? If it's just code within a tag then it's going to run as soon as the browser gets to that point.
You could possibly store some sort of cookie value or something after the FB.api call then check it on page load, but that seems like more work than is probably needed.

Do you want him to post it only once, ever?
If so, you're going to need to create a "state". In order to do this, you could do it client sided (with cookies), or server sided (with a database).
Create a boolean variable named "posted", and store it in a cookie or in a database (since you're using javascript, it's probably easier to use a cookie).
var posted=getCookie("posted");
if(!posted)
{
//call the FB.api();
setCookie("posted", true, duration);
}
Definition of setCookie and getCookie: http://www.w3schools.com/JS/js_cookies.asp

You could run a FQL query and check to see if the message has already been posted by querying the stream table with your app id. Something like:
<!DOCTYPE html>
<html>
<body>
<div id="fb-root"></div>
Post To Wall
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({ appId : '**yourAppID**', status : true, cookie : true, xfbml : true });
function postToWall() {
FB.login(function(response) {
if (response.session) {
FB.api(
{
method: 'fql.query',
query: 'SELECT post_id, message from stream where app_id = **yourAppID** and source_id = me()'
},
function(response) {
if(response.length == 0){
FB.ui(
{
method: 'feed',
name: 'Facebook Dialogs',
link: 'https://developers.facebook.com/docs/reference/dialogs/',
picture: 'http://fbrell.com/f8.jpg',
caption: 'Reference Documentation',
description: 'Dialogs provide a simple, consistent interface for applications to interface with users.',
message: 'Facebook Dialogs are easy!'
},
function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
}
else {
alert('User already posted this message');
}
}
);
}
} , {perms:''});
}
</script>
</body>
</html>

Related

Can't get facebook user's email using facebook javascript sdk

I'm using facebook authentication on my website using javascript sdk. I can get my email and name but I can't get their email, if they're loging in, only their name (it's my fb developer app).
It asks for the login, in case no one is logged in on facebook yet but get nothing happens. If I put an alert where it's supposed to login to my app and it indeed returns the name, just not the email. But if it's me I get both. Why's that?
Here's my code:
<%-- Facebook conection script--%>
<script src="//connect.facebook.net/en_US/all.js"></script>
<script> FB.init({
appId: '334351783684824',
cookie: true,
xfbml: true,
version: 'v2.8'
});
function fbAuthUser() {
FB.login(checkLoginStatus);;
}
function checkLoginStatus(response) {
if (response.status === 'connected') {
FB.api('/me', 'GET', { fields: 'email,name' }, function (response) {
alert(response.email + "; " + response.name);
Ajax(response.email, response.name);
});
}
}
function Ajax(expressao1, expressao2) {
var request = { email: expressao1, nome: expressao2 }
$.ajax({
url: 'login.aspx/LoginExterno',
method: 'post',
contentType: 'application/json',
data: JSON.stringify(request),
dataType: 'json',
success: function (resp) {
window.location.href = resp.d;
},
error: function () { }
})
}
</script>
It's supposed to login and, after getting the data, use that ajax function to access a code behind c# function that redirects the user to the index, if he/she already has an account or to the registry if he/she doesn't have one. It doesn't even go in the Ajax function, because the email parameter is undefined, probably. But when both are present it does.
So, how can I get the email?
Ok, I finally got it. On on FB.Login function, I need to add the scope and the user has to give permission. On my code, it would be like:
FB.login(checkLoginStatus,{scope: 'email'});;

How to detect user cancelled share when using fb.ui

I'm using the documentation provided over here with the following code. The share dialog comes up correctly. The problem is that I'm not able to differentiate between "Cancel" and "Post" actions that the user takes on the dialog. I'd imagine this would be a part of the response.
FB.ui({
method: 'share',
href: 'https://developers.facebook.com/docs/',
}, function(response){
if (response && !response.error_code) {
console.log(response);
} else {
alert('Error while posting.');
}
});
edit: output from the console isn't doesn't provide any way of knowing
Cancel - Object {e2e: "{"submit_0":1401181811121}"}
Post - Object {e2e: "{"submit_0":1401181815112}"}
I tested this, and apparently there's some info in the response object you could use to determine if the dialog was cancelled.
Code
FB.ui({
method: 'share',
href: 'https://developers.facebook.com/docs/'
}, function(response){
if (response && !response.error_code) {
console.log("OK: "+JSON.stringify(response));
} else {
console.log("Not OK: "+JSON.stringify(response));
}
});
Output upon cancellation:
{error_code: 4201, error_message: "User+canceled+the+Dialog+flow", e2e: "{"submit_0":1401188820613}"}
So, I guess you could check for cancellaction like this:
FB.ui({
method: 'share',
href: 'https://developers.facebook.com/docs/'
}, function(response){
if (response && !response.error_code) {
console.log("OK: "+JSON.stringify(response));
} else if (response && response.error_code === 4201) { //Cancelled
console.log("User cancelled: "+decodeURIComponent(response.error_message));
} else {
console.log("Not OK: "+JSON.stringify(response));
}
});
Unfortunately, FB.Events.subscribe() doesn't offer an Event for the Cancallation of this dialog: https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/v2.0
This is intentionally so as to dissuade developers from using posting as a gating mechanism. It should be up to the person to choose whether to post or not, it should not be a requirement of the app.
Use "feed" method instead of "share" so that it doesn't require app permission to get the response.
FB.ui({
method: 'feed',
caption: 'My Caption',
link: 'http://www.google.com/'
}, function(response) {
if (response && response.post_id) {
alert('Thank you for sharing!');
} else {
alert('You have cancelled the share.');
}
});
I also have a problem with the response function, I'm currently coding and trying to use fb.UI
return FB.ui({
method: 'share',
href: this.shareUrl,
hashtag: "myHashTag",
quote: "myQuote"
}, function(res) {
console.log("res = ", res);
console.log("res? = ", res != null);
return App.vent.trigger("FBShareView:cancelled");
});
I'm finding that on a successful share, res is an empty array and res != null is true
I'm finding that for the cancel scenario, res is undefined.
I expected to see res as an object with an error_message as described here: https://developers.facebook.com/docs/sharing/reference/share-dialog
Could you tell me what may be going wrong please?

Simple Facebook Javascript post to stream example?

I'm trying to post to user stream, without user prompt. I cannot manage to find a code that works. Facebook JSDK is already loaded and I will insert the code inside:
FB.getLoginStatus(function(response){
to make sure the user is already logged to my application. Could you provide an example of publishing to the user stream using the publish_stream permission?
With Dialog
You need to use the Feed Dialog, with FB.ui():
function postToFeed() {
// calling the API ...
var obj = {
method: 'feed',
link: 'https://developers.facebook.com/docs/reference/dialogs/',
picture: 'http://fbrell.com/f8.jpg',
name: 'Facebook Dialogs',
caption: 'Reference Documentation',
description: 'Using Dialogs to interact with users.'
};
function callback(response) {
document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
}
FB.ui(obj, callback);
}
Documentation: https://developers.facebook.com/docs/reference/dialogs/feed/
Without Dialog
To make a post without the Dialog you need to use the FB.api():
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);
}
});
Documentation: https://developers.facebook.com/docs/reference/javascript/FB.api/
Direct URL
https://www.facebook.com/dialog/feed?
app_id=APP_ID&
link=https://YOUR_DOMAIN&
picture=http://YOUR_DOMAIN/image.jpg&
name=Facebook%20Dialogs&
caption=API%20Dialogs&
description=Using%20Dialogs%20to%20interact%20with%20users.&
redirect_uri=http://YOUR_DOMAIN/response
Documentation: https://developers.facebook.com/docs/reference/dialogs/feed/

Facebook JS - FB.api() only posts message, not media attachment

I'm trying to post to the active users wall with a mp3 attachment. It works fine from
Facebook's Test Console (see below), but when I call it from my mobile app, It only posts the message. What am I missing here :(
Facebook's Test Console: http://developers.facebook.com/docs/reference/rest/stream.publish/
Here is my JS...
Login
FB.login(
function(response) {
if (response.authResponse) {
alert('logged in');
} else {
alert('not logged in');
}
},{ scope: "email,user_likes,publish_stream,offline_access" } //added offline_access to see if that was the problem
);
Post to wall with attachment
var attachment = {
'message': 'testing',
'attachment': {'media': [{
'type': 'mp3',
'src': 'http://www.looptvandfilm.com/blog/Radiohead%20-%20In%20Rainbows/01%20-%20Radiohead%20-%2015%20Step.MP3',
'title': 'Test Title',
'artist': 'My Artist',
'album': 'My Album' }]}
};
FB.api('/me/feed', 'post', attachment, function(response) {
if (!response || response.error) {
alert(response.error.message);
} else {
alert('Post ID: ' + response.id);
}
});
var attachment = {
'message': 'testing',
'source': 'http://www.looptvandfilm.com/blog/Radiohead%20-%20In%20Rainbows/01%20-%20Radiohead%20-%2015%20Step.MP3'
};
This will post the mp3 to your feed allowing a user to click a play button inline. See working example here: http://jsfiddle.net/dmcs/aggJc/1/
As you will note, that when you POST data to the Graph API, the formatting is different than when you GET the same object back. Posting is kinda shorthand notation version and the Getting is the long hand.

Is there an event in the Facebook JavaScript SDK that fires after a user has commented?

I'm using the following to display a coupon for users that have liked my company's page via a Facebook 'Like' button on your page.
FB.Event.subscribe('edge.create',
function(response) {
// action
}
);
};
When a user clicks the 'Like' button the box appears asking if they want to post it to their wall with a message and the callback takes place at this time to display the coupon.
Is there a callback that occurs after the user has posted (or opted not to post)?
I use something like this for posts then check the response:
<script>
function fb_share() {
FB.ui({
method: 'feed',
name: 'Name of App',
link: 'http://YOURLINK.com',
picture: 'someurltoimage.jpg',
description: 'Your description of the post for the wall!'
},
function(response) {
if (response && response.post_id) {
console.debug(response.post_id);
// Post was published - now lets send it to our ouwn custom processing page on our server
$.post('/process-post',{uid: <?php echo $currentUser; ?>, wallpost: response.post_id},function(resp) {
// callback after storing the requests
});
} else {
// Post was not published;
}
});
return false;
}
</script>

Categories

Resources