Saturday, May 21, 2016

SharePoint 2013 REST API CRUD Operations

SharePoint 2013 new OData Rest web service API  that would let us to communicate with SharePoint list items. In the below code, I had written REST web api that would perform CRUD operations on list items. The example uses JavaScript on button click action.


[code]<%@ Page Inherits="System.Web.UI.Page" MasterPageFile="~masterurl/default.master" Title="REST Demo" meta:progid="SharePoint.WebPartPage.Document" %>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <script type='text/javascript'>
  //Retrieve list items 
$(document).ready(function () {
     $("#getItem").click(function (event) { 
     retrieve();
     });  

     //Insert new item
     $("#addNewItem").click(function (event) {
     var name = document.getElementById('txtItem').value;
     var addNewItemUrl = "/_api/Web/Lists/GetByTitle('Northwind')/Items";
     var data = {__metadata: { 'type': 'SP.Data.NorthwindListItem' }, Title: name};
     addNewItem(addNewItemUrl,data);        
     });        

 

     //Update new item
     $("#updateItem").click(function(event){  
     var updateItemUrl = "/_api/Web/Lists/getbytitle('Northwind')/getItemById(4)";
     var data = {__metadata: { 'type': 'SP.Data.NorthwindListItem' }, Title: 'Joe'}; 
     updateNewItem(updateItemUrl,data)
     });  

     //Delete item
     $("#deleteItem").click(function(event){  
     var url = "/_api/Web/Lists/getbytitle('Northwind')/getItemById(4)";
     deleteitem(url);
     });
});

function retrieve() {
 $.ajax({
            url: "http://sharepoint2013.gcm.com/sites/RBSSharePoint/_api/Web/Lists/GetByTitle('Northwind')/Items",
            type: "GET",
            headers: {
                "accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },

            success: function (data) {      
            var results = data.d.results;
             for (i = 0; i < data.d.results.length; i++) {
             var item = data.d.results[i];
             $("#ResultDiv").append(item.Title + "\t" + item.Continent+"<br>" );
             }
            },

            error: function (error) {
                       $("#ResultDiv").append(JSON.stringify(error));
            }
            });
}

function addNewItem(url,data) {
$.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "POST",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose"
        },

        data: JSON.stringify(data),
        success: function (data) {
            console.log(data);
        },

        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}

function deleteitem(url) {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "DELETE",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose",
            "IF-MATCH": "*"
        },

        sucess: onSucess,
        error: onError
    });
}

function updateNewItem(updateItemUrl,payload) {
$.ajax({
   url: _spPageContextInfo.webAbsoluteUrl + updateItemUrl,
   type: "POST",
   headers: { "Accept": "application/json;odata=verbose",
      "X-RequestDigest" : $("#__REQUESTDIGEST").val(),
      "X-HTTP-Method": "MERGE",
      "If-Match": "*"},
   data: JSON.stringify(payload),
   contentType: "application/json;odata=verbose",
   success: function (data) {
  console.log(data);
},

error: function (error) {
alert(JSON.stringify(error));
}
});
}

function onSucess(data) {
    alert(data + 'Item Deleted');
}

function onError(error) {
    alert(JSON.stringify(error));
}

 

</script>
    <div id="MainContent">
    <P>
      <button id="createList">Create list</button>
      <button id="addNewItem">Insert Item</button>
     </p>
     <p>

   <button id="updateItem">Update Item</button>
   <button id="deleteItem">Delete Item</button>
   <button id="getItem" type="button">Retrieve Item</button>
     </p> 
     <p style="text-align:justify"> 
      <input type="text" id="txtItem"/>
     </p>
     <p>
     <div id="ResultDiv">
     </div>
     </p></div>
</asp:Content>[/code]

No comments:

Post a Comment