12:56 pm
March 19
Publish Actions with Facebook Javascript SDK
( 4 Votes )
Written by: Rohan Makkar Views : 6023

In the previous article, we learnt how to create a Facebook app, authenticate an user and access his basic information like email and friends. Now in this second part of the tutorial series, we will learn how to publish status/photo through Graph API. For this tutorial, we would need to ask for two more permissions i.e publish_stream, user_photos.

If using Facebook Login Button

<div class="fb-login-button" autologoutlink="true" data-show-faces="false" data-width="200"
data-max-rows="1" size="medium" scope="email,publish_stream,user_photos">

If using FB.login method
function login() {
    FB.login(function (response) {
        if (response.authResponse) {
            // connected                    
        } else {
            // cancelled
        } 
    }, { scope: 'email,publish_stream,user_photos' });
}

demojsapp-facebook-publish-interface

<body>
    <div style="float: left; margin-right: 20px">
    <div class="fb-login-button" autologoutlink="true" data-show-faces="false" data-width="200"
        data-max-rows="1" size="medium" scope="email,publish_stream,user_photos">
    </div>
    <div id="emailDiv">
        Your Email</div>
    <br />
    Your Friends
    <ul>
        <li id="friend1">Friend 1</li>
        <li id="friend2">Friend 2</li>
        <li id="friend3">Friend 3</li>
    </ul>
    <input id="inviteFriends" type="button" value="Invite Friends" onclick="inviteFriends()" />
    </div>
    <div>
        <textarea id="textArea" cols="40" rows="4"></textarea><br />        
        <input id="shareStatus" type="button" value="Set Status" onclick="setStatus()" />
        <input id="giveFeedback" type="button" value="Give Feedback" onclick="giveFeedback()" /><br />
        <input id="shareStatusUI" type="button" value="Set Status (UI)" onclick="setStatusThroughFBUI()" />
        <input id="giveFeedbackUI" type="button" value="Give Feedback (UI)" onclick="giveFeedbackThroughFBUI()" /><br />
        <input id="imageURL" type="text" size="30"/>
        <button id="attachPhoto" onclick="attachPhoto()">Attach Photo</button>
    </div>    
</body>

Sorry for not being able to think a real time scenario, however, I would try my best to keep this article as general as possible so that many could be benefited.

1 Set Status

Publishing a status update on user's profile is easy. We just need to do a simple POST request to '/me/feed'.

function setStatus() {
            var text = document.getElementById("textArea").innerHTML;
            FB.api('/me/feed', 'post', { message: text }, function (response) {
                if (!response || response.error) {
                    alert(response.error.message);
                } else {
                    alert('Post ID: ' + response.id);
                }
            });
        }

publish-feed-fb-api

A link can also be published with this method -

function setStatusWithLink() {
    var text = document.getElementById("textArea").value;    
    FB.api('/me/feed', 'post', {
        message: text,
        link: 'http://www.loginworks.com/',
        picture: 'http://www.loginworks.com/images/stories/Blog-Images/create-facebook-app.png',
        name: 'My new status',
        caption: 'Updated my status through Javascript sdk',
        description: text
    }, function (response) {
        if (!response || response.error) {
            alert(response.error.message);
        } else {
            alert('Post ID: ' + response.id);
        }
    });
}

publish-feed-link-fb-api

When successfully posted, Facebook returns post id of the newly updated status which you might want to store in database for own research/analytics. In this example, we posted the status on click of a button from the user but this can be totally automated i.e without any user interaction.

2 Give Feedback

Rather than posting on user's own wall, you might want to share it on some page, for example allowing users to post feedback about your app on the app page. This can be easily done by using page_id instead of /me in the api call above.

function giveFeedback() {
            var text = document.getElementById("textArea").innerHTML;
            FB.api('/lognow/feed', 'post', {
                message: text
            }, function (response) {
                if (!response || response.error) {
                    alert(response.error.message);
                } else {
                    alert('Post ID: ' + response.id);
                }
            });
        }

publish-feed-page-api-fb

NOTE: As of February 6, 2013, you can no longer use this method to post on Friends Timeline. As an alternative you can use Open Graph Actions or Feed Dialog (explained below).

3 Set Status (UI)

If posting on behalf of user is not a necessity, then you can also consider Feed Dialogs. Feed Dialogs are designed to prompt users to share share links on their profile's feed. Developers can provide custom link that is to be shared - a name, picture, caption and description can be attached to the link. Further more, a user can write a message for the link. Final post is similar to the link shared via FB.api, the only difference is that the text for message parameter is written by user.

function setStatusThroughFBUI() {
    var text = document.getElementById("textArea").value;
    var obj = {
        method: 'feed',        
        link: 'http://www.facebook.com/lognow',
        picture: 'http://www.loginworks.com/images/stories/Blog-Images/create-facebook-app.png',
        name: 'My feedback to a page',
        caption: 'Posting to a page through Javascript sdk',
        description: text
    };

    function callback(response) {
        alert("Post ID: " + response['post_id']);
    }

    FB.ui(obj, callback);
}

Like the FB.api calls explained above, Facebook will return the post_id of the newly posted feed story.

publish-feed-feed-dialog

publish-feed-feed-dialog-timeline

4 Give Feedback (UI)

You can also use the Feed Dialog to post stories on a page by adding a to parameter.

function giveFeedbackThroughFBUI() {
    var text = document.getElementById("textArea").value;           
    var obj = {
        method: 'feed',
        to: 'lognow',
        link: 'http://www.facebook.com/lognow',
        picture: 'http://www.loginworks.com/images/stories/Blog-Images/create-facebook-app.png',
        name: 'My feedback to a page',
        caption: 'Posting to a page through Javascript sdk',
        description: text
    };

    function callback(response) {
        alert("Post ID: " + response['post_id']);
    }

    FB.ui(obj, callback);
}

publish-feed-page-feed-dialog

The value of the to parameter can be the id of a page or a user. So, you can replace the page_id with a user_id or a user_name. Remember, user_id must correspond to a user who is a friend of the currently logged in user.

function postToFriendThroughFBUI() {
    var text = document.getElementById("textArea").value;
    var obj = {
        method: 'feed',
        to: 'friend_user_id',
        link: 'http://www.facebook.com/lognow',
        picture: 'http://www.loginworks.com/images/stories/Blog-Images/create-facebook-app.png',
        name: 'My Post to a Friend',
        caption: 'Posting to a friend\'s timeline through Javascript sdk',
        description: text
    };

    function callback(response) {
        alert("Post ID: " + response['post_id']);
    }

    FB.ui(obj, callback);
}

publish-feed-friend-feed-dialog

publish-feed-friend-feed-dialog-timeline

5 Attach Photo

Now let us post a photo to the user's profile through Graph API.

function attachPhoto() {
    var text = document.getElementById("textArea").value;
    var imgURL = document.getElementById("imageURL").value;
    FB.api('/me/photos', 'post', {
        message: text,
        url: imgURL
    }, function (response) {
        if (!response || response.error) {
            alert(response.error.message);
        } else {
            alert('Post ID: ' + response.id);
        }
    });
}

photo-post-fb-api

This will create a new album with the same name as of the app (if it didn't existed already) and the photo will be added in that album. You can also add a photo to a particular album by specifying the album id in the following endpoint: 'Album_ID/Photos'. Once posted, Facebook will return the photo_id as response.  

6 Invite Friends

Another very attractive feature of the Graph API, that I would love to demonstrate is sending app invites to friends. It is one of the great ways to increase your app users. You can either invoke the Request dialog to allow user to choose the desired friends through MultiFriendSelector or you can specify the comma-separated user_ids in the to parameter.

Invoking via MultiFriendSelector (i.e absence of to parameter)
function inviteFriendsViaMultiFriendSelector() {
    FB.ui({ method: 'apprequests',
        message: 'Request to use my app'
    }, requestCallback);
}

function requestCallback(response) {
    // Handle callback here
    alert("Total requests sent: " + response.to.length);
}
Invoking by specifying user_ids
function inviteFriends() {
    FB.ui({ method: 'apprequests',
        message: 'Request to use my app',
        to: 'comma-seperated-user_ids'
    }, requestCallback);
}

function requestCallback(response) {
    // Handle callback here
    
}

app-requests-fb-api

7 Handling Errors

Like any other development framework, you may be confronted with some exceptions while working with Graph API.

a) OAuthException #200 "The user hasn't authorized the application to perform this action"

The user has not granted the necessary permissions. Ask him/her to login again.
You can always check if the user has granted the necessary permission or not before making an API call.

function setStatus() {
    FB.api('/me/permissions', function (response) {
        
        var perms = response.data[0];

        if (perms.publish_stream) {
		
            var text = document.getElementById("textArea").innerHTML;
            FB.api('/me/feed', 'post', { message: text }, function (response) {
                if (!response || response.error) {
                    alert(response.error.message);
                } else {
                    alert('Post ID: ' + response.id);
                }
            });
			
        } else {
            // User DOESN'T have permission. Perhaps ask them  to login again
            FB.login(function(response) {
		console.log(response);
	}, { scope: "publish_stream" });
        }
    });
}
b) OAuthException #100 "Missing message or attachment"

Your value for message parameter is null.

Hope this article helped you. Post your doubts/feedbacks in the comment section below.
Be updated with the latest tech tutorials by subscribing to RSS Feeds.



Examples/Tutorial: Publishing to User Profile Feed through Graph API in Facebook Javascript SDK
( 4 Votes )