Skip to content

Instantly share code, notes, and snippets.

@rheid
Created December 7, 2014 16:40
Show Gist options
  • Save rheid/170f2401951adf9da83d to your computer and use it in GitHub Desktop.
Save rheid/170f2401951adf9da83d to your computer and use it in GitHub Desktop.
Post a SharePoint Newsfeed
var feedManagerEndpoint;
// Get the SPAppWebUrl parameter from the query string and build
// the feed manager endpoint.
$(document).ready(function () {
var appweburl;
var params = document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var param = params[i].split("=");
if (param[0] === "SPAppWebUrl") appweburl = param[1];
}
feedManagerEndpoint = decodeURIComponent(appweburl)+ "/_api/social.feed";
postToMyFeed();
});
// Publish a post to the current user's feed by using the
// "<app web URL>/_api/social.feed/my/Feed/Post" endpoint.
function postToMyFeed() {
$.ajax( {
url: feedManagerEndpoint + "/my/Feed/Post",
type: "POST",
data: JSON.stringify( {
'restCreationData':{
'__metadata':{
'type':'SP.Social.SocialRestPostCreationData'
},
'ID':null,
'creationData':{
'__metadata':{
'type':'SP.Social.SocialPostCreationData'
},
'ContentText':'This post was published using REST.',
'UpdateStatusText':false
}
}
}),
headers: {
"accept": "application/json;odata=verbose",
"content-type":"application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: getMyFeed,
error: function (xhr, ajaxOptions, thrownError) {
alert("POST error:\n" + xhr.status + "\n" + thrownError);
}
});
}
// Get the current user's feed by using the
// "<app web URL>/_api/social.feed/my/Feed" endpoint.
function getMyFeed() {
$.ajax( {
url: feedManagerEndpoint + "/my/Feed",
headers: {
"accept": "application/json;odata=verbose"
},
success: feedRetrieved,
error: function (xhr, ajaxOptions, thrownError) {
alert("GET error:\n" + xhr.status + "\n" + thrownError);
}
});
}
// Parse the JSON data and iterate through the feed.
function feedRetrieved(data) {
var stringData = JSON.stringify(data);
var jsonObject = JSON.parse(stringData);
var feed = jsonObject.d.SocialFeed.Threads;
var threads = feed.results;
var feedContent = "";
for (var i = 0; i < threads.length; i++) {
var thread = threads[i];
var participants = thread.Actors;
var owner = participants.results[thread.OwnerIndex].Name;
feedContent += '<p>' + owner +
' said "' + thread.RootPost.Text + '"</p>';
}
$("#message").html(feedContent);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment