I want to create a webpart which can post data to a specific Sharepoint's news feed, but have been unable to locate any good documentation. The only link I found was:
https://msdn.microsoft.com/library/e9ad06a1-831d-8ed0-c76e-8b049f14216f%28Office.15%29.aspx
My question is: what method can I use to post data to a Sharepoint-site's news feed?
In the link they mention that you can post to "the URL of a site feed". Is that the same as a news feed? Anyone who has done something similar?
We can use JSOM or REST API to achieve it.
REST API:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function(){
$.ajax( {
url: weburl + "/_api/social.feed/my/Feed/Post",
type: "POST",
data: JSON.stringify({
'restCreationData':{
'__metadata':{
'type':'SP.Social.SocialRestPostCreationData'
},
'ID': null,
'creationData':{
'__metadata':{
'type':'SP.Social.SocialPostCreationData'
},
'ContentText': "the post content text",
'UpdateStatusText':false
}
}
}),
headers: {
"accept": "application/json;odata=verbose",
"content-type":"application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(){
console.log("success to post ");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("POST error:\n" + xhr.status + "\n" + thrownError);
}
});
});
</script>
JSOM:
<script type="text/javascript" src="/_layouts/15/sp.userprofiles.js"></script>
<script type="text/javascript">
SP.SOD.executeOrDelayUntilScriptLoaded(WritePost, 'SP.UserProfiles.js');
function WritePost() {
var oclientContext;
var ofeedManager;
var oresultThread;
// Initialize the current client context and the SocialFeedManager instance.
oclientContext = SP.ClientContext.get_current();
ofeedManager = new SP.Social.SocialFeedManager(oclientContext);
// Add a link to be included in the post.
var olinkDataItem = new SP.Social.SocialDataItem();
olinkDataItem.set_itemType(SP.Social.SocialDataItemType.link);
olinkDataItem.set_text('My blog url');
olinkDataItem.set_uri('http://sundarnarasiman.net');
var osocialDataItems = [ olinkDataItem ];
// Set up the post content
var opostCreationData = new SP.Social.SocialPostCreationData();
opostCreationData.set_contentText('The text for the post, which contains a {0}.');
opostCreationData.set_contentItems(osocialDataItems);
// Write the post
oresultThread = ofeedManager.createPost(null, opostCreationData);
oclientContext.executeQueryAsync(WriteSucceeded, WriteFailed);
}
function WriteSucceeded(sender, args) {
//$get("ResultMessage").innerText = 'Successfully posted the message to Posts';
}
function WriteFailed(sender, args) {
//$get("ResultMessage").innerText = 'Failure in writing message' + args.get_message();
}
</script>
Refer to:
Post/Reply a post by Social feed REST API in SharePoint 2013
How to publish a post to SharePoint Social Feed using SharePoint 2013 JSOM
Related
I am trying to read image column in spfx using rest and nojS. THe site modern. I am unable to get the exact url. There are other properties like server relative url is returned. However is it possible to get the image and then it can be bound to image control?
You can convert json data into objects(My image column name is img).
var obj = eval('(' + data.d.img + ')');
$("#img").attr("src", obj.serverRelativeUrl);
I test with js, It should be similar in SPFX, you can refer to it.
Full test code:
<img id="img">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function () {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('test3')/items(17)",
method: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: function (data) {
var obj = eval('(' + data.d.img + ')');
$("#img").attr("src", obj.serverRelativeUrl);
$("#img").attr("style", "width:50px;height:50px;")
}
});
})
</script>
Test result:
I upload a file to sharepoint and trying to update its metadata, but I always get error 400 in last step.
As far as I understand, sharepoint only handles lists and items. A "folder" is a list and both metadata and files inside are items. And a "file" is a list and its metadata are items.
Documentation about updating metadata say about to make a POST request to:
https: // {site_url} / _api / web / lists / GetByTitle ('{list_title}') / items ({item_id})
Updating files must be done by PUT method (not MERGE allowed), but updating metadata must be done specifically by MERGE method. I have tried both, and both failed.
This is my current updating metadata request, but I'm continuing getting an error 400.
var data = {
"__metadata": {
"type":type
},
"Description":"lorem ipsum"
};
var headerToken = {
headers: {
'Authorization':'Bearer ' + token
, 'X-HTTP-Method':'MERGE'
, 'Accept':'application/json;odata=verbose'
, 'Content-Type':'application/json;odata=verbose'
, 'Content-Length':JSON.stringify(data).length
, 'If-Match': etag
, 'X-RequestDigest': digest
}
};
try {
var response = await axios.post(
'https://{site_url}/_api/web/lists/GetByTitle("'+MY_FOLDER+'")/items('+id+')'
, JSON.stringify(data)
, headerToken
);
return response;
}
type, etag and id are get from uploading file response and digest is get from a request to contextinfo endpoint. MY_FOLDER is a test library and at this moment is a constant.
You need to use single quotes in getbytitle.
"https://{site_url}/_api/web/lists/GetByTitle('"+MY_FOLDER+"')/items("+id+")"
Updated:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
UpdateFolder()
function UpdateFolder(){
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Doc')/items(30)",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose",
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
},
data: "{__metadata:{'type':'SP.Data.DocItem'},test:'test'}",
/*where Title is column name and add your desired new data*/
success: function(data) {
console.log(data);
},
error: function(error) {
alert(JSON.stringify(error));
}
});
}
})
</script>
Is there a way to add a Navigation node in Quick Launch below a given node (not as a child) using SharePoint Rest API
Sample code for your reference:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
$(document).ready(function ($) {
$("#createQuickLaunch").click(function () { createQuickLaunch() });
});
//Create a Quicklaunch Navigation
function createQuickLaunch() {
var endPointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/navigation/QuickLaunch";
var headers = {
"accept": "application/json;odata=verbose",
"content-Type": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
}
var call = jQuery.ajax({
url: endPointUrl,
type: "POST",
data: JSON.stringify({
"__metadata": { type: "SP.NavigationNode" },
'IsExternal': true,
'Title': "Bing",
'Url': "http://www.bing.com"
}),
headers: headers
});
call.done(successHandler);
call.fail(failureHandler);
}
function successHandler(data, textStatus, jqXHR) {
SP.UI.Notify.addNotification("Navigation created Successully", false);
}
function failureHandler(errorMessage) {
alert("Request Failed: unable to Navigation: " + JSON.stringify(errorMessage));
}
</script>
<input type="button" title="createQuickLaunch" value="createQuickLaunch" id="createQuickLaunch"/>
Reference:
Add Quick Launch Link To SharePoint 2013 Site Using REST API
I have a problem with my Google Sign in.
I follow the steps on Google Sign-In for server-side apps
After all this step, i have this html file that run on a server :
<!DOCTYPE html>
<html itemscope itemtype="http://schema.org/Article">
<head>
<link rel="stylesheet" href="theme.css">
<!-- BEGIN Pre-requisites -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
<!-- END Pre-requisites -->
<script>
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: 'CLIENT_ID'
});
});
}
</script>
</head>
<body>
<button id="googleBtn">Connect</button>
<script>
$('#googleBtn').click(function() {
auth2.grantOfflineAccess().then(googleCallback);
});
</script>
<script>
function googleCallback(authResult) {
if (authResult['code']) {
console.log(authResult);
} else {
console.log(authResult);
}
}
</script>
</body>
</html>
This first part work perfectly (I think), when I click on button, a window popup, I select an account and I get a code. So now, I want to get email and profile, so I make this request in nodejs to exchange the code with an access token.
var form = {
code: 'XXXXXXXXXXXX',
client_id: 'CLIENT_ID,
client_secret: 'CLIENT',
grant_type:'authorization_code'
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'https://www.googleapis.com/oauth2/v4/token',
body: formData,
method: 'POST'
}, function (err, rep, body) {
console.log(err);
console.log(rep.statusCode);
console.log(body);
});
But in response, I have this
{
"error": "redirect_uri_mismatch",
"error_description": "Bad Request"
}
And I don't understand why, because I don't use any redirect_uri in primary request in html file. I have try some cases like add redirect_uri on Console API and in request, but I have the same result...
Can you help me ?
From a client side auth2.grantOfflineAccess process, to get accessToken on server, you have to pass redirect_uri=postmessage in request params.
From your example :
var form = {
code: 'XXXXXXXXXXXX',
client_id: 'CLIENT_ID,
client_secret: 'CLIENT',
grant_type:'authorization_code',
redirect_uri: 'postmessage' // the line to add
};
You need to define your callback url to Google via console.developer.google.com
So you need to follow this steps for define the callback URL:
Go to console.developer.google.com
Select your project.
Click 'Credentials' on the left menu.
Click your client on the 'OAuth 2.0 client IDs' list.
Add your callback url to 'Authorized redirect URIs' list.
And done.
My node.js web-app is using microsoft's ocr computer vision api
https://www.microsoft.com/cognitive-services/en-us/computer-vision-api
When I pass a static link to the api, it works
like:
body: "{'url':'LINK_TO_IMAGE'}",
this is the part of the request callback.
What I want is to pass links dynamically.
So that the callback function is evoked the variable link
I have tried using this:
body: {'url':link},
but this does not work, there is no response.
Is there any other format I should follow?
Look document, here https://dev.projectoxford.ai/docs/services/54ef139a49c3f70a50e79b7d/operations/5527970549c3f723cc5363e4
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
"language": "unk",
"detectOrientation ": "true",
};
$.ajax({
url: "https://api.projectoxford.ai/vision/v1/ocr?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{subscription key}");
},
type: "POST",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>