Update SharePoint List Item using Rest API and HTML Input Element - sharepoint-2013

I am having a difficult time trying to get my below script to work for updating items on my SharePoint list “ProjectTracker”. I researched and tried several similar methods, but I can’t seem to get the any script version to update the list item(s). I continually receive the SharePoint error message “value”: This type SP.ListItemEntityCollection does not support HTTP PATCH method.” Statue”:400,”statusText”:”Bad Request”}. I included a screen grab of the error and below is the script I am using.
Any help or advice will be greatly appreciated. Thank you in advance.
jQuery(document).on("click", '#UpdateListItem', function(){
UpdateListItem();
});//Button close
function UpdateListItem() {
var myID = $("#itemID").val();
var listName = "ProjectTracker";
var office = $("#uOffice").val();
var title = $("#uProjectTitle").val();
var priority = $("#uPriority").val();
var startDate = $("#uStartDate").val();
var assignedTo = $("#uAssignedTo").val();
var status = $("#uStatus").val();
var requestor = $("#uRequestor").val();
var item = {
"__metadata": { "type": "SP.Data.ProjectTrackerListItem" },
"Office": office,
"ProjectTitle": title,
"Priority": priority,
"StartDate": startDate,
"AssignedTo": assignedTo,
"Status": status,
"Requestor": requestor
};
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items(" + myID + ")",
type: "POST",
data: JSON.stringify(item),
headers: {
contentType: "application/json;odata=verbose",
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method":"MERGE",
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
alert('List Item Updated');
}
function onError(error) {
alert(JSON.stringify(error));
}
}//Function close

Please check list internalname and column internal name
For more details with AJAX call refer below age for full ajax call l.
https://sharepointmasterhub.blogspot.com/2020/12/sharepoint-crud-operations-with-rest-api.html?m=1#Update

Related

Getting list of Sharepoint Site Collections - OnPrem 2016. Console.log is empty

I'm tyring to get a list of all the site collections that users have permissions to access. My plan is to display these on the home page, to make it easy for them to navigate to each of their sites. I've tried the following code, but nothing form my API call is writing the the console. It's just blank. What am I missing with writing to the console? Is the name siteURL wrong?
'''
$.ajax({
url: "/_api/search/query?querytext='contentclass:sts_site'",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var results = data.d.results;
var itemhtml = "";
$.each(results, function (index, dataRec) {
console.log(siteUrl);
});
},
error: function (data) {
(data);
}
})
'''
Here is a code snippet to get all site collection and print using Console.log:
<script src="https://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$( document ).ready(function() {
//print sites info
searchSites(_spPageContextInfo.webAbsoluteUrl,
function(query){
var resultsCount = query.PrimaryQueryResult.RelevantResults.RowCount;
for(var i = 0; i < resultsCount;i++) {
var row = query.PrimaryQueryResult.RelevantResults.Table.Rows.results[i];
var siteUrl = row.Cells.results[6].Value;
console.log(JSON.stringify(siteUrl));
}
},
function(error){
console.log(JSON.stringify(error));
}
);
});
function searchSites(webUrl,success, failure) {
var url = webUrl + "/_api/search/query?querytext='contentclass:sts_site'";
$.ajax({
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data.d.query);
},
error: function (data) {
failure(data);
}
});
}
</script>
Reference:
What is the REST endpoint URL to get list of site collections?

Parsing nested elements from JSON response using a postman test script

I'm using the following Postman test script to check and log the status of a POST.
pm.environment.unset("uuid");
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("uuid", jsonData.id);
var base = pm.request.url
var url = base + '/status?uuid=' + pm.environment.get("uuid");
var account = pm.request.headers.get("account")
var auth = pm.request.headers.get("Authorization")
pm.test("Status code is 200",
setTimeout(function() {
console.log("Sleeping for 3 seconds before next request.");
pm.sendRequest ( {
url: url,
method: 'GET',
header: {
'account': account,
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': auth
}
},
function (err, res) {
console.log(res.json().messageSummary);
})
},3000)
);
The script is able to make the call and retrieve the messageSummary from the response:
{
"id": "3c99af22-ea07-4f5d-bfe8-74a6074af71e",
"status": "SUCCESS",
"token": null,
"messageSummary": "[2] Records uploaded, please check errors/warnings and try again.",
"data": [
{
"ErrorCode": "-553",
"ErrorMessage": "Error during retrieving service service_id entered"
}
]
}
I'm wanting to also get the nested ErrorMessage, but so far everything I've tried comes back undefined or throws an error.
I assumed console.log(res.json().data[1].ErrorMessage) would work, but, alas, it does not.
UPDATE: arrays start with [0] not [1]...
pm.environment.unset("uuid");
var jsonData = pm.response.json();
pm.environment.set("uuid", jsonData.id);
var base = pm.request.url
var url = base + '/status?uuid=' + pm.environment.get("uuid");
var account = pm.request.headers.get("account")
var auth = pm.request.headers.get("Authorization")
setTimeout(function() {
console.log("Sleeping for 3 seconds before next request.");
pm.sendRequest ( {
url: url,
method: 'GET',
header: {
'account': account,
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8',
'Authorization': auth
}
},
function (err, res) {
console.log(res.json().messageSummary);
console.log(res.json().data[0].ErrorCode + ': ' + res.json().data[0].ErrorMessage)
})
},3000)
You would need to change the [1] to [0] to fix that reference.

How to get the total number of Items in a specific view in a list using rest api

I have requirement to get the total number of items in a specific view
in a SharePoint list.
I am trying below end point but it is returning count of all item in a
list.
/_api/Web/Lists/GetByTitle('<list_name>')/Items
let say view name is XYZ and list name is ABC how to build a rest api
to get total count of items in XYZ view from ABC list?
To get the item count in a specific list view, firstly get the list view CAML Query, then use this CAML Query with Post Request in Rest API to return items, here is a code snippet for your reference:
<script type="text/javascript">
getListItemsForView(_spPageContextInfo.webAbsoluteUrl,'ABC','XYZ')
.done(function(data)
{
var itemsCount = data.d.results.length;
alert(itemsCount);
})
.fail(
function(error){
console.log(JSON.stringify(error));
});
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);
});
}
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"
}
});
}
</script>
Reference:
Using REST to fetch SharePoint View Items
You can do it either way, using CAML Query and using same filters as list view or using filters in your Rest API URL.
For details please check https://sharepoint.stackexchange.com/a/266795/68021

How can I get list items by view name, using REST API ajax?

I tried to get a list of items from the Sharepoint library by view name. I had ajax rest API URL:
url: webapp + "_api/web/list/getbytitle" + "('" + LibraryName + "')/View/getbytitle" +"('" + viewName + "')"
method:"GET"
header:"Accept":"application/json;odata=verbose
How can I get all the items in view name?
please refer the following code snippet to get items from specific view, Rest API not provider items endpoint return from a view directly.
So please do the following:
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:
getListItemsForView(_spPageContextInfo.webAbsoluteUrl,'MyList12','View1')
.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));
});
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);
});
}
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"
}
});
}
Same question has been answered here:
Using REST to fetch SharePoint View Items

Get multiple list items by ID in SharePoint List

I am trying to retrieve a list items from a SharePoint list but my issue is that I would like to retrieve the last four items by ID and I don't know how to proceed using JSOM.
Can someone help me whit some CAML code on how to do that?
var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();
//Geting reference to the list
var olist = web.get_lists().getByTitle('Configs');
var oitem = olist.getItemById(1);
//get Title,id,ConfigItem fields
ctx.load(oitem, "Title", "Id", "ConfigItem");
ctx.executeQueryAsync(function () {
alert(oitem.get_item("Title"));
alert(oitem.get_item("ConfigItem"));
}, function (a, b) {
alert(b.get_message());
});
You could use rest api with order by and $top option for this requirement.
/_api/web/lists/getbytitle('chart')/items?$select=ID,Title&$orderby= ID desc&$top=4
Rest api get list items.
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('chart')/items?$select=ID,Title&$orderby= ID desc&$top=4",
type: "GET",
headers:
{
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose"
},
success: function (data) {
for (var i = 0; i < data.d.results.length; i++) {
var item = data.d.results[i];
//to do
}
},
error: function (data) {
console.log(data.responseJSON.error);
}
});
Here is JSOM solution with use of CamlQuery.
var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();
var query = new SP.CamlQuery()
query.set_viewXml("<View><Query><OrderBy><FieldRef Name='ID' Ascending='FALSE' /></OrderBy></Query><RowLimit>4</RowLimit></View>")
var list = web.get_lists().getByTitle('Configs');
var items = list.getItems(query, "ID", "Title", "FirstName", "LastName", "Level", "Grade", "Date");
var dictionary = [];
ctx.load(items);
ctx.executeQueryAsync(function () {
var enumerator = items.getEnumerator();
while (enumerator.moveNext()) {
var item = enumerator.get_current();
dictionary.push({
title: item.get_item("Title"),
firstName: item.get_item("FirstName"),
lastName: item.get_item("LastName"),
level: item.get_item("Level"),
grade: item.get_item("Grade"),
date: item.get_item("Date"),
});
}
}, function (a, b) {
alert(b.get_message());
});