Saturday, 14 April 2018

CRUD Operation On List Items Using REST API Services In SharePoint 2013

Introduction 

SharePoint 2013 has greatly expanded the REST services available to developers. With this, we have much more SharePoint functionality exposed via JSOM and Web Services. The goal of this article is to provide how to perform basic create, read, update, and delete (CRUD) operations on lists and list items with the REST services.

SharePoint REST endpoint Overview:
The following table contains typical REST endpoint URL examples to get you started working with SharePoint data. Prepend http://server/site/_api/ to the URL fragments shown in the table to construct a fully qualified REST URL. Below is a list of the basic commands used to get List Items from a SharePoint List through the SharePoint 2013 REST Services.
URL endpointDescriptionSupported HTTP Method
/_api/Web/Lists/ getbytitle('listname')Getting a list details by its title and updating it as well. Ifanyone changes your list title, your code will break.GET, POST
/_api/Web/Lists(guid'guid id of your list')Same as above but changing list title will not affect the code.GET, POST
/_api/Web/Lists/getbytitle(' listname ')/FieldsRetrieving all fields associated with a list and add new fieldsGET, POST
/_api/Web/Lists/getbytitle('listname')/
Fields/getbytitle('fieldname')
Getting details of a field, modifying and deleting it.GET, PUT, PATCH, MERGE, DELETE
/_api/Web/Lists/getbytitle('listname')
/Items
Retrieving all items in a list and adding new itemsGET, POST
/_api/web/lists/getbytitle('listname')
/GetItemById(itemId)
This endpoint can be used to get, update and delete a single item.GET, PUT, PATCH, MERGE, DELETE
/_api/lists/ getbytitle (‘'listname')/items?$orderby=TitleOrder Your ResultsGET, POST
/_api/lists/ getbytitle (‘'listname')/items?$select=Title,IdRetrieve Selected Column Data valueGET, POST
/_api/web/lists/getbytitle('listname')/Items/
?$select=Title,FieldName/Id&$expand= FieldName /Id
Retrieving the lookup valueGET, POST

Now, I will demo all the operations on list items, including retrieve, create, update and delete on list items.


List Name: PracticeList
Fields: EmpName(Title), Father Name(Father_x0020_Name)



<table>
   <tbody>
      <tr>
         <td>Employee Name:</td>
         <td> 
            <input type="text" name="EmployeName"  id="txtEmpName"/> 
         </td>
      </tr>
      <tr>
         <td>Father Name:</td>
         <td> 
            <input type="text" name="FatherName" id="txtFatherName"/> 
         </td>
      </tr>
  
   <tr>
         <td col=2>
<input type="submit" value="Add" id="btAdd">
<input type="submit" value="Update" id="btUpdate">
<input type="submit" value="View" id="btView">
<input type="submit" value="Delete" id="btDelete">
</td>
         
      </tr>
 
   </tbody>
</table>
<div id="ResultDiv">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">  

$(document).ready(function(){
    $('input[id*="btAdd"]').click(function(){
      AddListItem();
    });

$('input[id*="btUpdate"]').click(function(){
      UpdateListItem();
    });

$('input[id*="btDelete"]').click(function(){
      DeleteItem();
    });

$('input[id*="btView"]').click(function(){
      FetchAllItems();
    });

});

function AddListItem()  
{  
var listName="PracticeList";
    var Title = $("#txtEmpName").val();  
    var FatherName = $("#txtFatherName").val();  
var itemType = GetItemTypeForListName(listName);  
var item = {
        "__metadata": { "type": itemType },
        "Title": Title,
"Father_x0020_Name": FatherName
    };
 
    $.ajax  
        ({  
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('PracticeList')/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)  
        {  
            alert('Success');  
        },  
        error: function(data)  
        {  
alert('Error'); 
            $("#ResultDiv").empty().text(data.responseJSON.error);  
        }  
    });  
}

function UpdateListItem()  
{  

var listName="PracticeList";

    var FatherName = $("#txtFatherName").val();  
var itemType = GetItemTypeForListName(listName);  
var item = {
        "__metadata": { "type": itemType },
        "Father_x0020_Name": FatherName
    };
 
    $.ajax  
        ({  
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('PracticeList')/items('2')",  
        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": "*"
        },  
        success: function(data)  
        {  
            alert('Success');  
        },  
        error: function(data)  
        {  
alert('Error'); 
            $("#ResultDiv").empty().text(data.responseJSON.error);  
        }  
    });  
}

function DeleteItem()  
{  
var listName="PracticeList";   
 
    $.ajax  
        ({  
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items('7')",  
        type: "POST",  
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
             "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "X-HTTP-Method": "DELETE",
            "If-Match": "*"
        },  
        success: function(data)  
        {  
            alert('Success');  
        },  
        error: function(data)  
        {  
alert('Error'); 
            $("#ResultDiv").empty().text(data.responseJSON.error);  
        }  
    });  
}

function FetchAllItems()  
{  
var listName="PracticeList";   
 
    $.ajax  
        ({  
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items",  
        type: "GET",        
        headers: {
             "Accept": "application/json;odata=verbose"            
        },  
        success: function(data)  
        {  
            alert('Success'); 
var out = '<table>';
  
            for (var i = 0; i < data.d.results.length; i++)   
            {  
                var item = data.d.results[i];  
                
out+='<tr><td>"'+item.Title +'"</tr></td>';
            } 
out+='</table>';
document.getElementById("ResultDiv").innerHTML = out;
        },  
        error: function(data)  
        {  
alert('Error'); 
            $("#ResultDiv").empty().text(data.responseJSON.error);  
        }  
    });  
}


function GetItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}  


</script>  

No comments:

Post a Comment