SharePoint 2016 crud operations using Rest API and jQuery on SharePoint list or document library

crud operation using rest api in sharepoint 2013

This article we will deep dive on SharePoint 2016 List / Library CRUD operation with client side technologies like Rest API and jQuery. After completing this SharePoint 2016 tutorials you will get to know how we can do crud operations like create, read, update and delete operations in a list or document library using Rest API and jQuery.

crud operation using rest api in sharepoint 2013
crud operation using rest api in sharepoint 2013

Step 1:
Let us first create a SharePoint list with custom template with the below name & columns. The list has columns like:
– LoanNumber
– FirstName
– LastName
– LoanAmount

And the list looks like below:

update list item using rest api sharepoint 2013
update list item using rest api sharepoint 2013

Step 2:

Key aspects to be known before we implement CRUD with REST in client side object model.
– Retrieving Site URL



In SharePoint _spPageContextInfo.webAbsoluteUrl retrieves current site URL. You can read a SharePoint 2013 article on: _spPageContextInfo javascript or jquery variable in SharePoint 2013

– HTTP Methods in REST
– Reading list data (GET)
– Creating record/list item (POST)
– Updating list item (MERGE/PATCH/PUT)
– Delete list item (DELETE)

sharepoint 2013 rest api add list item
sharepoint 2013 rest api add list item

Step-3:
What is Request Digest in CSOM REST?
A replay attack occurs when a valid request is sent to the server and a copy of that request is stored. The request is then sent multiple times (replayed). This can result in a variety of different issues the most common of which is duplication of data. To prevent this, SharePoint requires the user to include a request digest value with each create, update and delete operation. This value is then used by SharePoint to identify non-genuine requests. Inside SharePoint Hosted apps, the request digest can be found by reading the value of the “__REQUESTDIGEST” object within the html page.

var digestValue = $(“#__REQUESTDIGEST”).val()

Note: this will only work on pages that contain the SharePoint Chrome element. The example above requires JQuery to work.

List Item Types:
To update or create list items you will need to include the list item type. This is a string automatically created by SharePoint when the list is first created. Two possible ways to obtain this are:



1. Perform a read operation on the list and locate the type within the returned set of elements. In JSON format the type can be found within the __metadata attribute of all of the returned list items. In Atom/xml format (the default format returned if you query from a web browser) you can find it in the category scheme attribute (labelled ‘term’) within the item.

2. You can attempt to generate the value from the list name. In general list item types follow the convention SP.Data.ListNameListItem (e.g. list name is “Test”, list item type is SP.Data.TestListItem). However this is not always the case. For example SharePoint automatically capitalises the first letter of the list name (e.g. list name “test” list item type is SP.Data.TestListItem). The following code snippet shows how to generate the List Item Type based on the list name.

Syntax:
function GetItemTypeForListName(name) {
return”SP.Data.” + name.charAt(0).toUpperCase() + name.slice(1) + “ListItem”;
}

CRUD Operations:
Create:
With the below code block we can add the new list item in “LoanInformation” SharePoint List

sharepoint 2013 rest api javascript example
sharepoint 2013 rest api javascript example

// CREATE Operation Modules ———————- START ———————-
$(“#btnAddLoans”).click(function () {
var url = _spPageContextInfo.webAbsoluteUrl;
var title = $(‘#txtLnID’).val();
var lnFstName = $(‘#txtFstNm’).val();
var lnLstName = $(‘#txtLstNm’).val();
var lnAmnt = $(‘#txtLnAmnt’).val();
createListItemWithDetails(“LoanInformation”, url, title,lnFstName,lnLstName,lnAmnt, function ()
{
alert(“Item has been created. Updating available items”);
$(‘#txtLnID’).val(“”);
$(‘#txtFstNm’).val(“”);
$(‘#txtLstNm’).val(“”);
$(‘#txtLnAmnt’).val(“”);
ReadLoans();

Read();
}, function () {
alert(“Ooops, an error occured. Please try again”);
});
});

function createListItemWithDetails(listName, siteUrl, title, lnFstName,lnLstName,lnAmnt,success, failure) {
var itemType = GetItemTypeForListName(listName);
var item = {
“__metadata”: {“type”: itemType },
“Title”: title,
“FirstName”:lnFstName,
“LastName”:lnLstName,
“LoanAmont”:lnAmnt
};

$.ajax({
url: siteUrl + “/_api/web/lists/getbytitle(‘” + listName + “‘)/items”,
type: “POST”,
contentType: “application/json;odata=verbose”,
data: JSON.stringify(item),
headers: {
“Accept”: “application/json;odata=verbose”,
“X-RequestDigest”: $(“#__REQUESTDIGEST”).val()
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}
// CREATE Operation Modules ———————- End ———————-



Edit / Update:
With the below code you can update the loan details of the selected loan number.

sharepoint 2013 rest api get list items jquery
sharepoint 2013 rest api get list items jquery

// Update Operation Releted Methods ———————- START ———————-
$( “.target” ).change(function() {
var selLnNumber = $(‘#chEditLnNumers’).find(“:selected”).val();
var requestUri = _spPageContextInfo.webAbsoluteUrl + “/_api/web/lists/getbytitle(‘LoanInformation’)/items?$filter=Title eq ‘” + selLnNumber+”‘”;
$.ajax({
url: requestUri,
type: “GET”,
headers: {
“accept”: “application/json; odata=verbose”
},
success: onSuccess,
error: onError
});

function onSuccess(data) {
var objItems = data.d.results;
for (var i = 0; i < objItems.length; i++) {
$(‘#txtEdLnID’).val(objItems[i].Title);
$(‘#txtEdFstNm’).val(objItems[i].FirstName);
$(‘#txtEdLstNm’).val(objItems[i].LastName);
$(‘#txtEdLnAmnt’).val(objItems[i].LoanAmont);
}
}
function onError(error) {
alert(‘Error’);
}
});

$(“#btnEditLoans”).click(function(){
var selLnNumber = $(‘#chEditLnNumers’).find(“:selected”).val();
updateListItem(selLnNumber, “LoanInformation”, _spPageContextInfo.webAbsoluteUrl, $(‘#txtEdLnID’).val(),$(‘#txtEdFstNm’).val(),$(‘#txtEdLstNm’).val(),$(‘#txtEdLnAmnt’).val(), function () {
alert(“Item updated, refreshing avilable items”);
$(‘#txtEdLnID’).val(“”);
$(‘#txtEdFstNm’).val(“”);
$(‘#txtEdLstNm’).val(“”);
$(‘#txtEdLnAmnt’).val(“”);
ReadLoans();
}, function () {
alert(“Ooops, an error occured. Please try again”);
});
});

function updateListItem(itemTitle, listName, siteUrl, title,lnFstName,lnLstName,lnAmnt, success, failure) {
var itemType = GetItemTypeForListName(listName);
var item = {
“__metadata”: { “type”: itemType },
“Title”: title,
“FirstName”:lnFstName,
“LastName”:lnLstName,
“LoanAmont”:lnAmnt
};

getListItemWithTitle(itemTitle, listName, siteUrl, function (data) {
$.ajax({
url: data.__metadata.uri,
type: “POST”,
contentType: “application/json;odata=verbose”,
data: JSON.stringify(item),
headers: {
“Accept”: “application/json;odata=verbose”,
“X-RequestDigest”: $(“#__REQUESTDIGEST”).val(),
“X-HTTP-Method”: “MERGE”,
“If-Match”: data.__metadata.etag
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}, function (data) {
failure(data);
});
}

// Update Operation Releted Methods ———————- END ———————-

Delete:
With the below code we can delete the selected loan number.

sharepoint 2013 rest api get list items examples
sharepoint 2013 rest api get list items examples

// Delete Operation Modules ———————- START ———————-

$(“#btnDel”).click(function () {
var selLnNumber = $(‘#chLnNumers’).find(“:selected”).val();
//alert(selLnNumber);
var itemId = $(‘#DeleteItems’).val();
deleteListItem(selLnNumber, “LoanInformation”, _spPageContextInfo.webAbsoluteUrl, function () {
alert(“Item deleted, refreshing avilable items”);
ReadLoans();
}, function () {
alert(“Ooops, an error occured. Please try again”);
});

});

function deleteListItem(itemTitle, listName, siteUrl, success, failure) {
getListItemWithTitle(itemTitle, listName, siteUrl, function (data) {
$.ajax({
url: data.__metadata.uri,
type: “POST”,
headers: {
“Accept”: “application/json;odata=verbose”,
“X-Http-Method”: “DELETE”,
“X-RequestDigest”: $(“#__REQUESTDIGEST”).val(),
“If-Match”: data.__metadata.etag
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
},
function (data) {
failure(data);
});
}

// Delete Operation Modules ———————- End ———————-

Complete Output:

sharepoint 2013 rest api get list items javascript
sharepoint 2013 rest api get list items javascript

Hope this helps. Happy coding in SharePoint….!!!

Find the complete code to perform CRUD operations.


You May Also like the Following SharePoint Online Tutorials:

About Krishna Vandanapu

I am Krishna.Vandanapu a SharePoint architect working in IT from last 12 years, I worked in SharePoint 2007, 2010, 2013, 2016 and Office 365. I have extensive hands on experience in customizing SharePoint sites from end to end. Expertise in SharePoint migration tools like Sharegate, Doc Ave and Metalogix. Migrated SharePoint sites from SharePoint 2007 to 2010 and 2010 to 2013 several times seamlessly. Implementing CSOM with Microsoft best practices. Spent quality time in configuring SharePoint application services like User Profile, Search, Managed Meta data services etc. Now exploring SharePoint Framework and SharePoint 2019

View all posts by Krishna Vandanapu →