CRUD operations in sharepoint REST API Using Jquery AJAX

0
472
views

Download Source Code: CRUD

In this article I have explain how to perform create, read, update, and delete operations of sharepoint list items using HTTP requests.

Target Audience: Sharepoint beginners

        HTTP Request            Usage
               GET This method helps to fetch the information from sharepoint list
              POST This method helps to create or update the list items in sharepoint list

PUT: Required all the object properties to update the resources

Merge: Optional to required all the object properties to update the resources

         PUT/MERGE This method helps to update the existing object using X-HTTP method
           DELETE This method helps to delete the object from sharepoint list

 

Open sharepoint site,

Create a list name “Employee” to play Create, Read, Update, Delete Operations using HTTP Requests

“POST” method used to create Item in the sharepoint list

 URL: http://<Sharepoint SiteURL>/_api/web/lists/Getbytitle(listname)/items

function createListItem() {
 //Fetch the values from the input elements 
 var eName = $('#txtempname').val();
 var eDesg = $('#txtdesignation').val();
 var eEmail = $('#txtemail').val();
 var eMobile = $('#txtmobile').val();
 var eBloodGroup = $('#txtbloodgrp').val();
 var eComAddress = $('#txtaddress').val();
 var eEmergency = $('#txtemergency').val();

$.ajax({
 async: true, // Async by default is set to “true” load the script asynchronously 
 // URL to post data into sharepoint list 
 url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee')/items",
 method: "POST", //Specifies the operation to create the list item 
 data: JSON.stringify({
 '__metadata': {
 'type': 'SP.Data.EmployeeListItem' // it defines the ListEnitityTypeName 
 },
 //Pass the parameters 
 'EmployeeName': eName,
 'Designation': eDesg,
 'Email': eEmail,
 'Mobile': eMobile,
 'BloodGroup': eBloodGroup,
 'CommunicationAddress': eComAddress,
 'EmergencyContact': eEmergency
 }),
 headers: {
 "accept": "application/json;odata=verbose", //It defines the Data format 
 "content-type": "application/json;odata=verbose", //It defines the content type as JSON 
 "X-RequestDigest": $("#__REQUESTDIGEST").val() //It gets the digest value 
 },
 success: function(data) {
 swal("Item created successfully", "success"); // Used sweet alert for success message 
 },
 error: function(error) {
 console.log(JSON.stringify(error));
}
})
}

“GET” Method used to Fetch the list items from the sharepoint list

URL: http://<Sharepoint SiteURL>/_api/web/lists/Getbytitle(listname)/items

function getItems() {
$.ajax({
async: true, // Async by default is set to “true” load the script asynchronously 
 url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee')/items", // URL to fetch data from sharepoint list 
 method: "GET", //Specifies the operation to fetch the list item
headers: {
 "accept": "application/json;odata=verbose", //It defines the Data format 
 "content-type": "application/json;odata=verbose" //It defines the content type as JSON
},
 success: function(data) {
 data = data.d.results;
 //Iterate the data 
 $.each(data, function(index, value) {
var html = "<tr><td>" + value.EmployeeName + "</td><td>" + value.Designation + "</td><td>" + value.Email + "</td> <
 td > " + value.BloodGroup + " < /td><td>" + value.CommunicationAddress + "</td >
 < td > " + value.EmergencyContact + " < /td><td>" + value.Mobile + "</td >
 < td > < a href = '#' data - target = '#ModalForUpdateEmployee' data - toggle = 'modal'
 onclick = 'edit(" + value.Id + ")' >
 < img src = 'https://sharepointtechie.sharepoint.com/sites/automatedwiki/SiteAssets/CRUD/003-edit-document.png' >
 < /a></td > < td > < a href = '#' onclick = 'deleteItem(" + value.Id + ");' >
 <img src = 'https://sharepointtechie.sharepoint.com/sites/automatedwiki/SiteAssets/CRUD/001-delete.png' > < /a></td >
 < /tr>"; 
 $('.table tbody').append(html); //Append the HTML
});
table = $('#subsiteList').DataTable(); //initialize the datatable
 },
 error: function(error) {
 console.log(JSON.stringify(error));
}
})
}

“MERGE” Method used to perform update the item in sharepoint list

URL: http://<Sharepoint SiteURL>/_api/web/lists/Getbytitle(listname)/items(itemid)

function update(uId) {
 //Fetch the values from the input elements
 var eName = $('#txtempnames').val();
 var eDesg = $('#txtdesignations').val();
 var eEmail = $('#txtemails').val();
 var eMobile = $('#txtmobiles').val();
 var eBloodGroup = $('#txtbloodgrps').val();
 var eComAddress = $('#txtaddresss').val();
 var eEmergency = $('#txtemergencys').val();
$.ajax({
 url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee')/items(" + uId + ")",
 method: "POST",
 data: JSON.stringify({
 '__metadata': {
 'type': 'SP.Data.EmployeeListItem'
 },
 'EmployeeName': eName,
 'Designation': eDesg,
 'Email': eEmail,
 'Mobile': eMobile,
 'BloodGroup': eBloodGroup,
 'CommunicationAddress': eComAddress,
 'EmergencyContact': eEmergency
 }),
 headers: {
 "accept": "application/json;odata=verbose",
 "content-type": "application/json;odata=verbose",
 "X-RequestDigest": $("#__REQUESTDIGEST").val(),
 "IF-MATCH": "*", //Overrite the changes in the sharepoint list item
 "X-HTTP-Method": "MERGE" // Specifies the update operation in sharepoint list
 },
 success: function(data) {
 swal("Item Updated successfully", "success");
 //Reninitialize the datatable when item updated
 if ($.fn.DataTable.isDataTable('#subsiteList')) {
 $('#subsiteList').DataTable().destroy();
 }
 $('#subsiteList tbody').empty();

//Bind the data into datatable
 getItems();
 },
 error: function(error) {
 console.log(JSON.stringify(error));
}
})
}

 “DELETE” method used to perform delete items in the sharepoint list

URL: http://<Sharepoint SiteURL>/_api/web/lists/Getbytitle(listname)/items(itemid)

function deleteItem(value) {
$.ajax({
 url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee')/items(" + value + ")",
 method: "POST",
 headers: {
 "accept": "application/json;odata=verbose",
 "content-type": "application/json;odata=verbose",
 "X-RequestDigest": $("#__REQUESTDIGEST").val(),
 "IF-MATCH": "*",
 "X-HTTP-Method": "DELETE"
 },
 success: function(data) {
swal("Deleted!", "Item Deleted successfully", "success");
 //Reinitialize the datatable 
 if ($.fn.DataTable.isDataTable('#subsiteList')) {
 $('#subsiteList').DataTable().destroy();
 }
 $('#subsiteList tbody').empty();
 getItems();
 },
 error: function(error) {
 console.log(JSON.stringify(error));
}
})
}

HTML Design For CRUD Operations
<div class="container">
 <div id="row4" class="row nopadding ">
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-horizontal padLeftRight">
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 pleft0 pright0">
 <div class="announcment paddingwebpart " style="background:white;">
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 pleft0 pright0">
 <h5 id="BtnAlign">
 <a class="addbtn" target="_blank" style="color:white; text-decoration:none" data-target="#ModalForNewProject" data-toggle="modal">New Employee</a>
 </h5>
 <br>
 </div>
 <table id="subsiteList" class="table table-striped table-bordered">
 <thead>
 <tr>
 <th>Employee Name</th>
 <th>Designation</th>
 <th>Address</th>
 <th>Email</th>
 <th>Blood Group</th>
 <th>Emergency Contact</th>
 <th>Mobile</th>
 <th>Edit</th>
 <th>Delete</th>
 </tr>
 </thead>
 <tbody></tbody>
 </table>
 </div>
 </div>
 </div>
 </div>
 <div class="modal fade" id="ModalForNewProject" role="dialog" title="Create new Project">
 <div class="modal-dialog">
 <fieldset>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 cls-contriute">
 <h5 class="contributtitle">Add Employee Information</h5>
 </div>
 </fieldset>
 <div id="ModelBody">
 <div class="form-horizontal well bs-component cls-divthoug" id="ModalValidation">
 <fieldset id="bodymodal">
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 cls-thought">Employee Name 
 <span class="red">*</span> 
 </label>
 </div>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 cls-thought">Designation 
 <span class="red">*</span> 
 </label>
 </div>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 cls-thought">Email 
 <span class="red">*</span> 
 </label>
 </div>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 cls-thought">Mobile 
 <span class="red">*</span> 
 </label>
 </div>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 cls-thought">Blood Group 
 <span class="red">*</span> 
 </label>
 </div>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 cls-thought">Address for communication 
 <span class="red">*</span> 
 </label>
 </div>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 cls-thought">Emergency contact 
 <span class="red">*</span> 
 </label>
 </div>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <div class="col-lg-offset-7 col-lg-2 cls-divbtn ">
 <input class="cls-savecancel" id="btnsave" type="button" onclick="createListItem();" value="Submit" />
 </div>
 <div class="col-lg-2 col-lg-offset-1">
 <input class="cls-savecancel" type="reset" value="Cancel" id="btnCancel" data-dismiss="modal" />
 </div>
 </div>
 </fieldset>
 </div>
 </div>
 </div>
 </div>
 <!-- update modal -->
 <div class="modal fade" id="ModalForUpdateEmployee" role="dialog" title="Update New Employee">
 <div class="modal-dialog">
 <fieldset>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 cls-contriute">
 <h5 class="contributtitle">Update Employee Information</h5>
 </div>
 </fieldset>
 <div id="ModelBody">
 <div class="form-horizontal well bs-component cls-divthoug" id="ModalValidation">
 <fieldset id="bodymodal">
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 cls-thought">Employee Name 
 <span class="red">*</span> 
 </label>
 </div>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 cls-thought">Designation 
 <span class="red">*</span> 
 </label>
 </div>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 cls-thought">Email 
 <span class="red">*</span> 
 </label>
 </div>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 cls-thought">Mobile 
 <span class="red">*</span> 
 </label>
 </div>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 cls-thought">Blood Group 
 <span class="red">*</span> 
 </label>
 </div>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 cls-thought">Address for communication 
 <span class="red">*</span> 
 </label>
 </div>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 cls-thought">Emergency contact 
 <span class="red">*</span> 
 </label>
 </div>
 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
 <div class="col-lg-offset-7 col-lg-2 cls-divbtn ">
 <input class="cls-savecancel" id="btnsave" type="button" onclick="update(uId);" value="Submit" />
 </div>
 <div class="col-lg-2 col-lg-offset-1">
 <input class="cls-savecancel" type="reset" value="Cancel" id="btnCancel" data-dismiss="modal" />
 </div>
 </div>
 </fieldset>
 </div>
 </div>
 </div>
 </div>

FULL CODE:
$(document).ready(function() {

getItems();

});

function createListItem() {
 var eName = $('#txtempname').val();
 var eDesg = $('#txtdesignation').val();
 var eEmail = $('#txtemail').val();
 var eMobile = $('#txtmobile').val();
 var eBloodGroup = $('#txtbloodgrp').val();
 var eComAddress = $('#txtaddress').val();
 var eEmergency = $('#txtemergency').val();
$.ajax({
async: true,
 url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee')/items",
 method: "POST",
 data: JSON.stringify({
 '__metadata': {
 'type': 'SP.Data.EmployeeListItem'
 },
 'EmployeeName': eName,
 'Designation': eDesg,
 'Email': eEmail,
 'Mobile': eMobile,
 'BloodGroup': eBloodGroup,
 'CommunicationAddress': eComAddress,
 'EmergencyContact': eEmergency
 }),
 headers: {
 "accept": "application/json;odata=verbose",
 "content-type": "application/json;odata=verbose",
 "X-RequestDigest": $("#__REQUESTDIGEST").val()
 },
 success: function(data) {
 var eName = $('#txtempname').val("");
 var eDesg = $('#txtdesignation').val("");
 var eEmail = $('#txtemail').val("");
 var eMobile = $('#txtmobile').val("");
 var eBloodGroup = $('#txtbloodgrp').val("");
 var eComAddress = $('#txtaddress').val("");
 var eEmergency = $('#txtemergency').val("");
swal("Item created successfully", "success");

if ($.fn.DataTable.isDataTable('#subsiteList')) {
 $('#subsiteList').DataTable().destroy();
 }
 $('#subsiteList tbody').empty();
 getItems();
 },
 error: function(error) {
 console.log(JSON.stringify(error));
}
})
}


function getItems() {
$.ajax({
async: true,
 url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee')/items",
 method: "GET",
headers: {
 "accept": "application/json;odata=verbose",
 "content-type": "application/json;odata=verbose"
},
 success: function(data) {
 data = data.d.results;
 console.log(data);
 $.each(data, function(index, value) {
var html = "<tr><td>" + value.EmployeeName + "</td><td>" + value.Designation + "</td>
<td>" + value.Email + "</td><td>" + value.BloodGroup + "</td><td>" + value.CommunicationAddress + "</td>
<td>" + value.EmergencyContact + "</td><td>" + value.Mobile + "</td>
<td><a href='#' data-target='#ModalForUpdateEmployee' data-toggle='modal' onclick='edit(" + value.Id + ")'>
<img src='https://sharepointtechie.sharepoint.com/sites/automatedwiki/SiteAssets/CRUD/003-edit-document.png'></a></td>
<td><a href='#' onclick='deleteItem(" + value.Id + ");'>
<img src='https://sharepointtechie.sharepoint.com/sites/automatedwiki/SiteAssets/CRUD/001-delete.png'></a>
</td></tr>";
 $('.table tbody').append(html);
});
   table = $('#subsiteList').DataTable();
 },
 error: function(error) {
 console.log(JSON.stringify(error));
}
})
}

function edit(value) {
$.ajax({
async: true,
 url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee')/GetItemByID(" + value + ")",
 method: "GET",
headers: {
 "accept": "application/json;odata=verbose",
 "content-type": "application/json;odata=verbose"
},
 success: function(data) {
 console.log(data.d.EmployeeName);
 eName = $('#txtempnames').val(data.d.EmployeeName);
 eDesg = $('#txtdesignations').val(data.d.Designation);
 eEmail = $('#txtemails').val(data.d.Email);
 eMobile = $('#txtmobiles').val(data.d.Mobile);
 eBloodGroup = $('#txtbloodgrps').val(data.d.BloodGroup);
 eComAddress = $('#txtaddresss').val(data.d.CommunicationAddress);
 eEmergency = $('#txtemergencys').val(data.d.EmergencyContact);
},
 error: function(error) {
 console.log(JSON.stringify(error));
}
 })
uId = value;
}


function update(uId) {
 var eName = $('#txtempnames').val();
 var eDesg = $('#txtdesignations').val();
 var eEmail = $('#txtemails').val();
 var eMobile = $('#txtmobiles').val();
 var eBloodGroup = $('#txtbloodgrps').val();
 var eComAddress = $('#txtaddresss').val();
 var eEmergency = $('#txtemergencys').val();
$.ajax({
 url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee')/items(" + uId + ")",
 method: "POST",
 data: JSON.stringify({
 '__metadata': {
 'type': 'SP.Data.EmployeeListItem'
 },
 'EmployeeName': eName,
 'Designation': eDesg,
 'Email': eEmail,
 'Mobile': eMobile,
 'BloodGroup': eBloodGroup,
 'CommunicationAddress': eComAddress,
 'EmergencyContact': eEmergency
 }),
 headers: {
 "accept": "application/json;odata=verbose",
 "content-type": "application/json;odata=verbose",
 "X-RequestDigest": $("#__REQUESTDIGEST").val(),
 "IF-MATCH": "*",
 "X-HTTP-Method": "MERGE"
 },
 success: function(data) {
 swal("Item Updated successfully", "success");
if ($.fn.DataTable.isDataTable('#subsiteList')) {
 $('#subsiteList').DataTable().destroy();
 }
 $('#subsiteList tbody').empty();
 getItems();
 },
 error: function(error) {
 console.log(JSON.stringify(error));
}
})
}


function deleteItem(value) {
$.ajax({
 url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee')/items(" + value + ")",
 method: "POST",
 headers: {
 "accept": "application/json;odata=verbose",
 "content-type": "application/json;odata=verbose",
 "X-RequestDigest": $("#__REQUESTDIGEST").val(),
 "IF-MATCH": "*",
 "X-HTTP-Method": "DELETE"
 },
 success: function(data) {
swal("Deleted!", "Item Deleted successfully", "success");
if ($.fn.DataTable.isDataTable('#subsiteList')) {
 $('#subsiteList').DataTable().destroy();
 }
 $('#subsiteList tbody').empty();
 getItems();
 },
 error: function(error) {
 console.log(JSON.stringify(error));
}
})
}

Final Result:

So In the above article you guys are easy to understand how to create, read, update, delete operations using HTTP Request
 Happy Sharepointing!…..

 

 

Please follow and like us:
0

LEAVE A REPLY

Please enter your comment!
Please enter your name here