How to get FB.api('/me/feed', 'post', ... to work? - javascript

I've tried to use FB.api to post something to my feed for hours now. I can't get it to work for me. I gave the permissions to the app. I can post to my feed with the PHP SDK but I have to use JavaScript.
<button onclick="doPost()">Post to Stream</button>
<script>
window.doPost = function() {
FB.api(
'/me/feed',
'post',
{ body: 'Trying the Graph' },
Log.info.bind('/me/feed POST callback')
);
};
</script>
Can someone give me the example of a simple HTML page that uses FB.api to post to a feed?

Well, I got it working myself. I'm not sure what was wrong the first time as I started from scratch with a new HTML file. I hope it will help someone:
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
</head>
<body>
Post to Facebook
<script>
function postToFacebook() {
var body = 'Reading Connect JS documentation';
FB.api('/me/feed', 'post', { body: body, message: 'My message is ...' }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response);
}
});
}
</script>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR APP ID GOES HERE',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>

I use this code on fb game-app
and looks like this http://trupa.files.wordpress.com/2012/04/prscreenan.jpg
<br><font style="color:#FFF; text-decoration:none;padding-left:27px;">post to wall</font><br>
<script>
function publishStory() {
FB.ui({
method: 'feed',
name: 'message name',
caption: 'message caption ',
description: 'description goes here',
link: 'the url current page',
picture: 'if you want to add an image'
},
function(response) {
console.log('publishStory response: ', response);
});
return false;
}
</script>

In first example you forgot "message" property. With out "message" you can post everyone, but not self.

Related

Using client.js library for Trello API

I'm new with trello API.
As suggested by Trello, I'm trying to use the client.js library.
I followed the instructions, and i get a 'Successful authentication' message in the console, but yet I get a 401 error(in the console):
POST https://api.trello.com/1/cards 401 () jquery-1.7.1.min.js:4
Here is my code:
<head>
<title>Trello api</title>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="https://api.trello.com/1/client.js?
key=[my key]"></script>
</head>
<body>
<script>
var authenticationSuccess = function() { console.log('Successful
authentication'); };
var authenticationFailure = function() { console.log('Failed
authentication'); };
Trello.authorize({
type: 'popup',
name: 'Getting Started Application',
scope: {
read: true,
write: true },
expiration: 'never',
success: authenticationSuccess,
error: authenticationFailure
});
var myList = 'my list';
var creationSuccess = function(data) {
console.log('Card created successfully. Data returned:' +
JSON.stringify(data));
};
var newCard = {
name: 'New Test Card',
desc: 'This is the description of our new card.',
idList: myList,
pos: 'top'
};
Trello.post("cards", newCard, creationSuccess);
</script>
Any ideas?
Thanks.
I had the same issue. I take 'login' and 'logout' from http://jsfiddle.net/A3Xgk/2/ , and it is working.
Trello.authorize({
interactive: false,
success: onAuthorize
});
$("#connectLink").click(function() {
Trello.authorize({
type: "popup",
success: onAuthorize
});
});
If it will not help, please write me, I give to you my code.

Email not able to retrieve from facebook javascript SDK [duplicate]

I am using JavaScript API to create my app for Facebook. The problem is, it's returning
email = undefined.
I don't know why? And if I use Facebook login/logout button on my app then the alert shows correct email id of the user but I don't want to do that.
What am I missing?
Here is my code:
<p><fb:login-button autologoutlink="true" perms="user_about_me,email"></fb:login-button></p>
<script>
window.fbAsyncInit = function () {
FB.init({ appId: '250180631699888', status: true, cookie: true,
xfbml: true
});
FB.getLoginStatus(function (response) {
if (response.session) {
greet();
}
});
};
(function () {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
} ());
function greet() {
FB.api('/me', function (response) {
alert('Welcome, ' + response.name + "!");
alert('Your email id is : '+ response.email);
});
}
</script>
// https://developers.facebook.com/docs/javascript/reference/FB.api/
// v2.4
FB.api('/me', { locale: 'en_US', fields: 'name, email' },
function(response) {
console.log(response.email);
}
);
here is example how i retrieve user name and e-mail:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
$(function() {
FB.init({
appId : 'APP_ID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
getCurrentUserInfo(response)
} else {
FB.login(function(response) {
if (response.authResponse){
getCurrentUserInfo(response)
} else {
console.log('Auth cancelled.')
}
}, { scope: 'email' });
}
});
function getCurrentUserInfo() {
FB.api('/me', function(userInfo) {
console.log(userInfo.name + ': ' + userInfo.email);
});
}
});
</script>
According to the latest info on the facebook page you should use 'scope' instead of perms.
https://developers.facebook.com/docs/reference/javascript/FB.login/
If you visit
https://developers.facebook.com/tools/console/
and use the fb-api -> user-info example as a starting point, then logout and back in again, it should ask you for email perms and you can see your email being printed. It is done using response.email as you mention in your post.
<button id="fb-login">Login & Permissions</button>
<script>
document.getElementById('fb-login').onclick = function() {
var cb = function(response) {
Log.info('FB.login callback', response);
if (response.status === 'connected') {
Log.info('User logged in');
} else {
Log.info('User is logged out');
}
};
FB.login(cb, { scope: 'email' });
};
</script>
Use this to for extra permission
for more details visit :
https://www.fbrell.com/examples/
In this code i have get user data form facebook and store into my database using ajax
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me?fields=email,name,first_name,last_name', function(response)
{
FB.api(
"/"+response.id+"/picture?height=100",
function (responses) {
//console.log(responses.data.url)
response['profile_pic']=responses.data.url;
$.ajax({
type:"POST",
url:'<?php echo base_url(); ?>'+'home/facebook_get_signup',
data:response,
success:function(res)
{
if(res=='success')
{
window.location='<?php echo base_url(); ?>';
}
if(res=='exists')
{
window.location='<?php echo base_url(); ?>';
}
}
});
}
)
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
// handle the response
}, {scope: 'email,user_likes'});
There are a couple of things wrong with your solution. First of all you are using the old authentication scheme. You should use the new one described here :
https://developers.facebook.com/docs/reference/javascript/
You need to add the oauth:true to your init function, and make sure that your getLoginStatus looks for the new type of response.
When that is said you need to make sure you have the right permissions to see the users e-mail. You can see the required permissions here:
http://developers.facebook.com/docs/reference/api/user/
You get those by using the FB.login function as described by TommyBs in another answer.
Once you have those options you can use the FB.api function to get the e-mail.

How to publish something on user's friend stream/wall in an application

In a Facebook application, I need to publish a user's friend stream a mlessage.
how can i figure out of that?
Thanks
send HTTP POST request to the following address https://graph.facebook.com/FRIEND_ID/feed
it returns the ID of posted message on success
here's the example code:
var msg = 'hello world';
FB.api('/YOUR_FRIEND_ID/feed', 'post', { message: msg }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
You can also use the javascript API for posting. The manual has sample code.
https://developers.facebook.com/docs/reference/javascript/FB.ui/
FB.ui(
{
method: 'feed',
to: friendId,
name: 'title',
link: 'http://host.com/title_link.com',
picture: 'http://host.com/image.jpg',
description: 'description',
caption: 'caption',
},
function(response) {
// Check for a posting to wall
if (response && response.post_id) {
// do some logging
}
}
});

facebook using jquerymobile frame work

I am trying to implement the basic features of facebook like updating the facebook profile, and also facebook login using jquerymobile frame work. Using this link http://thinkdiff.net/facebook/graph-api-javascript-base-facebook-connect-tutorial/
It works fine with HTML 5 format. But when I integrate with the JqueryMobile, I am getting an error which says Uncaught exception: cant call method appendChild.
I will paste the code here: please have a look and let me know whats the problem.
<body>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxxx', status: true, cookie: true, xfbml: true});
/* All the events registered */
FB.Event.subscribe('auth.login', function(response) {
// do something with response
login();
});
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
logout();
});
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
login();
}
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e); //i am getting error in the is line
});
function login(){
FB.api('/me', function(response) {
document.getElementById('login').style.display = "block";
document.getElementById('login').innerHTML = response.name + " succsessfully logged in!";
});
}
function logout(){
document.getElementById('login').style.display = "none";
}
//stream publish method
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: name,
caption: '',
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {
});
}
function showStream(){
FB.api('/me', function(response) {
//console.log(response.id);
streamPublish(response.name, 'Something ', 'hrefTitle', 'http://www.ffff.com', "Share www.ffffff.com");
});
}
function share(){
var share = {
method: 'stream.share',
u: 'http://www.fffffff.com'
};
FB.ui(share, function(response) { console.log(response); });
}
function graphStreamPublish(){
var body = 'hsdfkjasdkjfadkjf;adlfj';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
function fqlQuery(){
FB.api('/me', function(response) {
var query = FB.Data.query('select name, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
document.getElementById('name').innerHTML =
'Your name: ' + rows[0].name + "<br />" +
'<img src="' + rows[0].pic_square + '" alt="" />' + "<br />";
});
});
}
function setStatus(){
status1 = document.getElementById('status').value;
FB.api(
{
method: 'status.set',
status: status1
},
function(response) {
if (response == 0){
alert('Your facebook status not updated. Give Status Update Permission.');
}
else{
alert('Your facebook status updated');
}
}
);
}
</script>
<div data-role="page">
<div data-role="header">
<h1>Foofys-Facebook Page</h1>
</div><!-- /header -->
<div data-role="content">
<p>you are using foofys facebook app</p>
<div id="fb-root"></div>
<fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"> </fb:login-button>
<p>
Publish Wall Post |
<!-- Share With Your Friends | -->
Publish Stream |
<!-- FQL Query Example -->
</p>
<textarea id="status" cols="50" rows="5">Write your status here'</textarea>
<br />
<!-- Status Set Using Legacy Api Call -->
<br /><br /><br />
<div id="login" style ="display:none"></div>
<div id="name"></div>
</div><!-- /content -->
<div data-role="footer">
<h4>Page Footer</h4>
</div><!-- /footer -->
</div><!-- /page -->
</body>
i am not able to understand whats happening in the code, BTW I have just pointed where exactly I am getting the error.
The trick with JQM and FB api is to use the graph API. That is DO NOT use the simple javascript FB wrappers since they are unstable when exposed to JQM's page handling - instead just use the new graph / rest API, check for and avoid multiple inits of the FB core and your'e set. For instance
function updateUserInfo(uid, accessToken) {
var uri = "https://graph.facebook.com/" + uid;
console.log("About to call FP.api with URI " + uri);
$.ajax({
type: "GET",
url: "https://graph.facebook.com/" + uid,
dataType: "json",
success:
(function (response) {
console.log("About to call check profile ...");
$("#p_name").val(response.name);
$("#email").val(response.email);
$("#fb_id").val(response.id);
$.ajax({
type: "POST",
url: "/check_profile",
cache: false,
data: {fb_id: response.id},
success: onCheckSuccess,
error: onError
});
console.log("FB id: " + response.id);
}),
error: onError
});

Fb.api post to user wall only on login

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>

Categories

Resources