Basic CRUD Operations On List Item in SharePoint 2013

List of REST request properties used in this article:

URL:This is the REST resource endpoint URL.

Method/Type (GET, POST):

It’s a HTTP request method, where GET is for read operations and POST is for write operations. POST can perform updates or delete operations by giving a DELETE,MERGE verb in the X-HTTP-Method header.

Data/Body: This will be used in POST requests where we want to send data in the request body.

Headers:

X-RequestDigest:

If you aren’t using OAuth to authorize your requests, creating, updating, and deleting SharePoint entities require the server’s request form digest value as the value of the X-RequestDigest header.SharePoint-hosted add-ins can get the value from the #__REQUESTDIGEST page control available on the SharePoint page.

This you can find by inspecting element in your SharePoint webpage like below,

code

Accept:

The Accept header specifies the format of response data from the server. The default format is application/atom+xml. Here we will be using "accept":"application/json;odata=verbose" which can be parsed easily.

Content-type:

The Content-type header specifies the format of the data that the client is sending to the server. The default format is application/atom+xml. Here we will be using"content-type":"application/json;odata=verbose".

IF-MATCH:

This will used in POST requests for DELETE, MERGE, or PUT operations for changing lists and libraries. It provides a way to verify that the object being changed has not been changed since it was last retrieved. Or, lets you specify to overwrite any changes, as shown in the following Ex: "IF-MATCH":"*".

X-HTTP-Method:

This method will used in POST requests for DELETE, MERGE, or PUT operations.Used to specify that the request performs an Update or Delete operation. Ex: "X-HTTP-Method":"MERGE".

Usage of the above properties:

table

Apart from all these properties there is another important object called “spPageContextInfo”.This is very helpful when writing SP JavaScript code. It’s a simple object which you can find on every SharePoint page.This object is containing many properties which we can directly use in our code. Let’s see few of its properties.

  • webServerRelativeUrl
  • webAbsoluteUrl
  • siteAbsoluteUrl
  • serverRequestPath
  • layoutsUrl
  • webTitle
  • webTemplate
  • webLanguage
  • currentLanguage
  • currentCultureName
  • userId
  • userLoginName
  • systemUserKey
  • alertsEnabled
  • siteServerRelativeUrl Etc.,

    These you can see by inspecting the sharepoint page.

    page

    Among all the properties for this article I am going to use siteAbsoluteUrl to get my site url.

    Now let’s start working on CRUD operations one by one. We are going to use simple HTML and JavaScript in this article for easy understanding.

    In this article I have used a custom list called “ProductList” which containsfew basic columns as below.

    column
  1. Creating a list item

    a) HTML
    1. <divclass="container-wrap">  
    2.     <h2>Create a list item</h2>  
    3.     <table>  
    4.         <tr>  
    5.             <td>Title:</td>  
    6.             <td>  
    7.                 <inputtype="text" id="title" />  
    8.             </td>  
    9.         </tr>  
    10.         <tr>  
    11.             <td>Description:</td>  
    12.             <td>  
    13.                 <textareaid="description">  
    14.                     </textarea>  
    15.             </td>  
    16.         </tr>  
    17.         <tr>  
    18.             <td>Quantity:</td>  
    19.             <td>  
    20.                 <inputid="Quantity" type="text" />  
    21.             </td>  
    22.         </tr>  
    23.         <tr>  
    24.             <td>Price:</td>  
    25.             <td>  
    26.                 <inputid="Price" type="text" />  
    27.             </td>  
    28.         </tr>  
    29.         <tr>  
    30.             <td>City:</td>  
    31.             <td>  
    32.                 <inputid="City" type="text" />  
    33.             </td>  
    34.         </tr>  
    35.         <tr>  
    36.             <td>Availability:</td>  
    37.             <td>  
    38.                 <selectid="Availability">  
    39.                     <optionvalue="true">Yes</option>  
    40.                         <optionvalue="false">No</option>  
    41.                             </select>  
    42.         </tr>  
    43.         <tr>  
    44.             <td></td>  
    45.             <td>  
    46.                 <buttontype="button" onclick="AddNewItem()">Create</button>  
    47.             </td>  
    48.         </tr>  
    49.     </table>  
    50.     </div>  
    The above HTML looks like as below and fill the respective fields.

    create

    b) Write a JavaScript function as below on the button click action,

    1. functionAddNewItem()  
    2. {  
    3.     varTitle,  
    4.     Description,  
    5.     Quantity,  
    6.     Price,  
    7.     City,  
    8.     Availability;  
    9.     Title = $("#title").val();  
    10.     Description = $("#description").val();  
    11.     Quantity = $("#Quantity").val();  
    12.     Price = $("#Price").val();  
    13.     City = $("#City").val();  
    14.     Availability = $("#Availability").val();  
    15.   
    16.     varurl = _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('ProductList')/items";  
    17.     var data = JSON.stringify(  
    18.       {  
    19.         "__metadata":   
    20.         {  
    21.             "type""SP.Data.ProductListListItem"  
    22.         },  
    23.         "Title": Title,  
    24.         "Description": Description,  
    25.         "Quantity": Quantity,  
    26.         "Price": Price,  
    27.         "City": City,  
    28.         "Availability": Availability  
    29.     })  
    30.     $.ajax  
    31.     ({  
    32.         url: url,  
    33.         type: "POST",  
    34.         data: data,  
    35.         headers: {  
    36.             "Accept""application/json;odata=verbose",  
    37.             "Content-Type""application/json;odata=verbose",  
    38.             "X-RequestDigest": $("#__REQUESTDIGEST").val()  
    39.         },  
    40.         success: function(data)   
    41.       {  
    42.             alert("New list item has been created successfully.");  
    43.         },  
    44.         error: function(data)  
    45.         {  
    46.             alert("Failed to create list item.");  
    47.         }  
    48.     });  
    49. }  
    Now go to theSharePoint list and you will find a list item has been created in the list.

    product list

    Click on the product1 item to view its details,

    item

  2. Reading the list items

    a) Below is the simple HTML used for this and bind the list items dynamically using java script,

    1. <divclass="container-wrap">  
    2.     <h2>Get all List Items</h2>  
    3.     <buttontype="button" onclick="GetListItems()">Get Items</button>  
    4.         <tableid="GetItems" style="display:none">  
    5.             <thead>  
    6.                 <tr>  
    7.                     <td>Id</td>  
    8.                     <td>Title</td>  
    9.                     <td>Description</td>  
    10.                     <td>Quantity</td>  
    11.                     <td>Price</td>  
    12.                     <td>City</td>  
    13.                 </tr>  
    14.             </thead>  
    15.             <tbody>  
    16.                 <%-- Bind the tbody data here from script -- %>  
    17.             </tbody>  
    18.             </table>  
    19.             </div>  
    The above HTML looks like this.

    output

    b) Call JavaScript function on Get Items Click, 

    1. functionGetListItems()   
    2. {  
    3.     var row = "";  
    4.     varurl = _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('ProductList')/items";  
    5.     $.ajax  
    6.     ({  
    7.         url: url,  
    8.         type: "GET",  
    9.         headers:  
    10.         {  
    11.             "Accept""application/json;odata=verbose",  
    12.             "Content-Type""application/json;odata=verbose",  
    13.         },  
    14.         success: function(data)   
    15.         {  
    16.             var result = data.d.results;  
    17.             $.each(result, function(key, item)  
    18.             {  
    19.                 var l = item.Title;  
    20.                 row = row + '<tr><td>' + item.Id + '</td><td>' + item.Title + '</td><td>' + item.Description +  
    21.                     '</td><td>' + item.Quantity + '</td><td>' + item.Price +  
    22.                     '</td><td>' + item.City + '</td></tr>';  
    23.             })  
    24.   
    25.             $("#GetItems>tbody").html(row);  
    26.             $("#GetItems").show();  
    27.         },  
    28.         error: function(data)   
    29.         {  
    30.             alert("Failed to get list items.");  
    31.         }  
    32.     });  
    33.   
    34. }  

    Below is the items list you will get,


    list
  3. Update a list item

    To update a list item we need to pass the item Id to the REST resource endpoint URL.
    Here I am simply updating the Title and Price of the product by passing its Id for easy understanding.

    a) HTML
    1. <divclass="container-wrap" id="Update-Item">  
    2.     <h2>Update list item</h2>  
    3.     <table>  
    4.         <tr>  
    5.             <td>Id:</td>  
    6.             <td>  
    7.                 <inputtype="text" id="ItemId" />  
    8.             </td>  
    9.         </tr>  
    10.         <tr>  
    11.             <td>Title:</td>  
    12.             <td>  
    13.                 <inputtype="text" id="NewTitle" />  
    14.             </td>  
    15.         </tr>  
    16.         <tr>  
    17.             <td>Price:</td>  
    18.             <td>  
    19.                 <inputtype="text" id="NewPrice" />  
    20.             </td>  
    21.         </tr>  
    22.         <tr>  
    23.             <td></td>  
    24.             <td>  
    25.                 <buttontype="button" onclick="UpdateListItem()">Update</button>  
    26.             </td>  
    27.         </tr>  
    28.     </table>  
    29.     </div>  
    The above HTML looks like this.

    update

    b) Call JavaScript function on Update Click,
    1. functionUpdateListItem()  
    2. {  
    3.     var Id, Title, Price;  
    4.     Id = $("#ItemId").val();  
    5.     Title = $("#NewTitle").val();  
    6.     Price = $("#NewPrice").val();  
    7.   
    8.     varurl = _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('ProductList')/items(" + Id + ")";  
    9.     var data = JSON.stringify  
    10.     ({  
    11.         "__metadata":   
    12.         {  
    13.             "type""SP.Data.ProductListListItem"  
    14.         },  
    15.         "Title": Title,  
    16.         "Price": Price,  
    17.     })  
    18.     $.ajax  
    19.     ({  
    20.         url: url,  
    21.         type: "POST",  
    22.         data: data,  
    23.         headers: {  
    24.             "accept""application/json;odata=verbose",  
    25.             "content-type""application/json;odata=verbose",  
    26.             "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
    27.             "IF-MATCH""*",  
    28.             "X-HTTP-Method""MERGE"  
    29.         },  
    30.         success: function(data)  
    31.         {  
    32.             alert("List Item has been updated successfully")  
    33.         },  
    34.         error: function(data)   
    35.         {  
    36.             alert("Failed to update list items.");  
    37.         }  
    38.     });  
    39. }  
    This method updates the list item based on the ID of that particular list item,

    list

    Once you click on the list item you will get the list item which is updated.

    update

  4. Delete a list item

    In deleting list item will directly see the Ajax call by passing the list item id. Will use this API whenever we want to delete a list item by passing its ID.
    1. functionDeleteListItem()  
    2. {  
    3.     varurl = _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('ProductList')/items(1)";  
    4.     $.ajax  
    5.     ({  
    6.         url: url,  
    7.         method: "POST",  
    8.         headers:  
    9.         {  
    10.             "accept""application/json;odata=verbose",  
    11.             "content-type""application/json;odata=verbose",  
    12.             "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
    13.             "IF-MATCH""*",  
    14.             "X-HTTP-Method""DELETE"  
    15.         },  
    16.         success: function(data)   
    17.         {  
    18.             alert("List Item has been deleted successfully.")  
    19.         },  
    20.         error: function(data)  
    21.         {  
    22.             alert("Failed to delete the list item");  
    23.         }  
    24.     });  
    25. }  
    Open the list and u can find that the list item is deleted.

    deleted

Read more articles on SharePoint:

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now