Post reply on SharePoint online discussion board using REST API - rest

I am trying to post reply on a particular discussion of SharePoint online discussion board through REST API but unable to do it. I don't want to use SP.utilities as this REST API will be called from Android App.
Below is the code which I am implementing:
$.ajax({
url:"../_api/web/Lists/getbytitle(listname)/items?$filter=ParentItemID eq 40",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(itemProperties),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*"
},
success: function (data) {
alert("Successfully posted!!");
},
error: function (error) {
alert("error");
console.log(JSON.stringify(error));
}
});
Instead of creating reply inside discussion, it is creating a new discussion item.
Any help will be highly appreciated.

For creating a message item (reply) in Discussion Board the following properties needs to be specified:
FileSystemObjectType for a message items needs to be set to 0
ContentTypeId- content type Id of message item
ParentItemID - discussion item (container for messages) id
Regarding ParentItemID property
ParentItemID property could not be specified via message payload since it is a read only property, it means the following query for creating a message item fails:
Url /_api/web/lists/getbytitle('Discussions')/items
Method POST
Data {
'__metadata': { "type": "SP.Data.DiscussionsListItem" },
'Body': "Message text goes here",
'FileSystemObjectType': 0,
'ContentTypeId': '<MessageContentTypeId>',
'ParentItemID': <DiscussionItemId>
}
Solution
The following example demonstrates how to to create a message (reply) in Discussion Board via SharePoint REST API.
For creating a message under a discussion item (folder) the following
approach is used: once message item is created, it's getting moved
under a discussion item
var listTitle = "Discussions"; //Discussions Board title
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var messagePayload = {
'__metadata': { "type": "SP.Data.DiscussionsListItem" }, //set DiscussionBoard entity type name
'Body': "Message text goes here", //message Body
'FileSystemObjectType': 0, //set to 0 to make sure Message Item is created
'ContentTypeId': '0x0107008822E9328717EB48B3B665EE2266388E', //set Message content type
'ParentItemID': 123 //set Discussion item (topic) Id
};
createNewDiscussionReply(webUrl,listTitle,messagePayload)
.done(function(item)
{
console.log('Message(reply) has been sent');
})
.fail(function(error){
console.log(JSON.stringify(error));
});
where
function executeJson(options)
{
var headers = options.headers || {};
var method = options.method || "GET";
headers["Accept"] = "application/json;odata=verbose";
if(options.method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: options.url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if("data" in options) {
ajaxOptions.data = JSON.stringify(options.data);
}
return $.ajax(ajaxOptions);
}
function createListItem(webUrl,listTitle,payload){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";
return executeJson({
"url" :url,
"method": 'POST',
"data": payload
});
}
function moveListItem(webUrl,listTitle,itemId,folderUrl){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")?$select=FileDirRef,FileRef";
return executeJson({
"url" :url
})
.then(function(result){
var fileUrl = result.d.FileRef;
var fileDirRef = result.d.FileDirRef;
var moveFileUrl = fileUrl.replace(fileDirRef,folderUrl);
var url = webUrl + "/_api/web/getfilebyserverrelativeurl('" + fileUrl + "')/moveto(newurl='" + moveFileUrl + "',flags=1)";
return executeJson({
"url" :url,
"method": 'POST'
});
});
}
function getParentTopic(webUrl,listTitle,itemId){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")/Folder";
return executeJson({
"url" :url,
});
}
function createNewDiscussionReply(webUrl,listTitle, messagePayload){
var topicUrl = null;
return getParentTopic(webUrl,listTitle,messagePayload.ParentItemID)
.then(function(result){
topicUrl = result.d.ServerRelativeUrl;
return createListItem(webUrl,listTitle,messagePayload);
})
.then(function(result){
var itemId = result.d.Id;
return moveListItem(webUrl,listTitle,itemId,topicUrl);
});
}

Related

upload file into document library in sharepoint with column value

Iam trying to upload file into document library but I can able to upload file but however column data was not reflecting into the column of document library.using rest Api every thing is working but my column value was not showing inside the column
here is my code
function createListItem() {
debugger;
var files = $("#attachment")[0].files;
if (files.length > 0) {
fileName = files[0].name;
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var documentLibrary = "MyDocumets";
var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary;
// Construct the Endpoint
var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(#target)/Files/add(overwrite=true, url='" + fileName + "')?#target='" + targetUrl + "'&$expand=ListItemAllFields";
uploadFileToFolder(files[0], url, function(data) {
var file = data.d;
DocFileName = file.Name;
var updateObject = {
__metadata: {
type: file.ListItemAllFields.__metadata.type},
"DocumentType": $('#documenttype').val(),
"DocumentDescription": $("#Description").val(),
FileLeafRef: DocFileName //FileLeafRef --> Internal Name for Name Column
};
alert("File uploaded successfully!");
}, function(data) {
alert("File uploading failed");
});
} else {
alert("Kindly select a file to upload.!")
}
}
function uploadFileToFolder(fileObj, url, success, failure) {
var apiUrl = url;
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer(fileObj);
// Add the file to the SharePoint folder.
getFile.done(function(arrayBuffer) {
$.ajax({
url: apiUrl,//File Collection Endpoint
type: "POST",
data: arrayBuffer,
processData: false,
async: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
},
success: function(data) {
success(data);
},
error: function(data) {
success(data);
}
});
});
}
// Get the local file as an array buffer.
function getFileBuffer(uploadFile) {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function(e) {
deferred.resolve(e.target.result);
}
reader.onerror = function(e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(uploadFile);
return deferred.promise();
}
i wanted to know how to enter value into the column and upload the document at the sane time

Cannot get FileLeafRef property in SharePoint Rest API

Hi we are trying to retrieve the link URL of page in Site Pages using REST API the problem is that we cannot find the Name FileLeafRef property value.FileLeafReaf = null.
function fn_getListItems(webUrl,listTitle, queryText)
{
var viewXml = '<View><Query>' + queryText + '</Query></View>';
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
var queryPayload = {
'query' : {
'__metadata': { 'type': 'SP.CamlQuery' },
'ViewXml' : viewXml
}
};
return fn_executeJson(url,"POST",null,queryPayload);
}
function fn_getListViewItems(webUrl,listTitle,viewTitle)
{
var url = webUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery";
return fn_executeJson(url).then(
function(data){
var viewQuery = data.d.ViewQuery;
return fn_getListItems(webUrl,listTitle,viewQuery);
});
}
function fn_executeJson(url,method,headers,payload)
{
method = method || 'GET';
headers = headers || {};
headers["Accept"] = "application/json;odata=verbose";
if(method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if (typeof payload != 'undefined') {
ajaxOptions.data = JSON.stringify(payload);
}
return $.ajax(ajaxOptions);
}
Thanks.
SharePoint stores the full URL of a file in a hidden column EncodedAbsUrl.
So, you can request it explicitly as:
/_api/web/lists/getbytitle('Site Pages')/items?$select=*,EncodedAbsUrl
After that, you can directly use it somewhat as below, watch out for the quotes :
var items = data.d.results;
$.each(items, function(index, value) {
//Append results to DIV
$("#lstGlobalNews").append("<tr><td class='ms-vb2'><a href="+value.EncodedAbsUrl+" target='_blank'>"+value.Title+"</a></td><td class='ms-vb2' style='text-align: right;'>"+fn_FormatDate(value.Date_x0020_Posted)+"</td></tr>");
});
To retrieve FileLeafRef property, it needs to be explicitly specified in $select query option, for example:
/_api/web/lists/getbytitle('Site Pages')/items?$select=FileLeafRef
As alternative option it could also be retrieved via File resource, for example:
/_api/web/lists/getbytitle('Site Pages')/items?$select=File/Name&$expand=File
The FileLeafRef property only get the file name. If you want to get the file url, we need use ServerRelativeUrl property of file.
The REST API using this.
/_api/web/lists/getbytitle('Site%20Pages')/items?$select=File/ServerRelativeUrl&$expand=File

Reading ListItems inside folders from Sharepoint list( not library)

How to read sharepoint list items from a specific folders using Javascript/Jquery through JSOM or REST?
Using JSOM or CSOM, you need to specify 'FileDirRef' property in CAML Query, and add 'RecursiveAll' scope:
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(
'<View Scope="RecursiveAll"> " +
"<Query>" +
"<Where>" +
"<Eq>" +
"<FieldRef Name="FileDirRef" />" +
"<Value Type=\"Text\">yourFolderPath</Value>" +
"</Eq>" +
"</Where>" +
"</Query>" +
"</View>');
function GetFolders() {
var oWeb = _spPageContextInfo.webAbsoluteUrl;
var URLC = oWeb + "/_api/web/lists/getByTitle('ListName')/items";
$.ajax({
url: URLC,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
async: false,
cache: false,
success: function (data) {
$.each(data.d.results, function (index, item) {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('ListName/ListFolder)/listitemallfields/",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
async: false,
cache: false,
success: function (data) {
}
});
})
},
error: function (data) { }
});
}
You can use REST API to read list items from a specific folders using getfolderbyserverrelativeurl.
Refer below Code :
var folderRelativeUrl = "Relative_URL_Of_Your_Folder"; //here specify relative URL of your folder (e.g. '/Shared Documents')
getItemFromFolder().then(getItemFromFolderSuccess, getItemFromFolderFailed);
function getItemFromFolder(){
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfolderbyserverrelativeurl('" + folderRelativeUrl + "')/files?$expand=ListItemAllFields",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose"
}
});
}
function getItemFromFolderSuccess(data){
// success handler
var response = data.d.results; // This is Response Object from Server
}
function getItemFromFolderFailed(error){
// error handler code
}

Using REST to fetch SharePoint View Items

I am trying to construct the correct URL to return the items in a SharePoint View using the REST api.
Using my browser and the following URL I can return the items in the list.
https://mysharepoint.sharepoint.com/sites/MySite/_api/web/lists/getbytitle('Announcements')/Items
And I can get the view definition using the following URL.
https://mysharepoint.sharepoint.com/sites/MySite/_api/web/lists/getbytitle('Announcements')/Views/getbytitle('Latest News')/
But I cannot figure out what I need to put at the end of that URL to actually get the items that are returned by the the View.
SP.View object does not contain any methods for manipulating list items. But SP.View object contains SP.View.viewQuery property that specifies the query that is used by the list view. That means the following approach could be used for retrieving list items for view:
perform the first request to get CAML Query for List View using SP.View.viewQuery property
perform the second request to retrieve List Items by specifying CAML Query
How to return list items for a List View using REST API using JavaScript
function getJson(url)
{
return $.ajax({
url: url,
type: "GET",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose"
}
});
}
function getListItems(webUrl,listTitle, queryText)
{
var viewXml = '<View><Query>' + queryText + '</Query></View>';
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
var queryPayload = {
'query' : {
'__metadata': { 'type': 'SP.CamlQuery' },
'ViewXml' : viewXml
}
};
return $.ajax({
url: url,
method: "POST",
data: JSON.stringify(queryPayload),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose"
}
});
}
function getListItemsForView(webUrl,listTitle,viewTitle)
{
var viewQueryUrl = webUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery";
return getJson(viewQueryUrl).then(
function(data){
var viewQuery = data.d.ViewQuery;
return getListItems(webUrl,listTitle,viewQuery);
});
}
Usage
getListItemsForView(_spPageContextInfo.webAbsoluteUrl,'Announcements','Latest News')
.done(function(data)
{
var items = data.d.results;
for(var i = 0; i < items.length;i++) {
console.log(items[i].Title);
}
})
.fail(
function(error){
console.log(JSON.stringify(error));
});

How to send facebook api batch request with node.js

How do I send facebook api batch request with node.js?
FB's examples do not work.
but I finally got danwong/restler.js to work like this:
exports.updateUserFriends = function (userData, next) {
var TOKEN = userData[1];
var fbID = userData[3].id;
var batchreq = {};
batchreq.batch = [];
batchreq.batch.push({"method":"GET", "relative_url":fbID+"/"});
batchreq.batch.push({"method": "GET", "relative_url":fbID+"/friends?limit=50"});
restler.post('https://graph.facebook.com?access_token='+TOKEN,
{data:"batch="+JSON.stringify(batchreq.batch)})
.on('complete', function(data) {
console.log(data);
return next;
});
};
So I thought I'd post this to save someone else a bit of frustration.
First thing to note is that, "Only POST is allowed for batch requests" in FB Api.
var https = require('https');
var url = '/?access_token='+ YOUR_ACCESS_TOKEN_HERE,
batch=[{
"method":"GET",
"relative_url":page + "/insights"
}, {
"method": "GET",
"relative_url":page
}];
url = url + '&batch=' + JSON.stringify(batch);
console.log(url);
var options = {
host:'graph.facebook.com',
path:url,
method: 'POST'
};
var req =https.request(options, function(res){
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
var body='';
res.on('data', function(chunk){
// console.log("body:" + chunk);
body += chunk;
});
res.on('end', function(){
var fbRes = JSON.parse(body);
console.log(fbRes);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();