Wednesday, December 23, 2015

CRUD Operation Using REST API in SharePoint List with script editor Web Part.

CRUD Operation Using REST API in SharePoint List with script editor.

The goal of this blog is to perform CRUD operation in SharePoint List using REST API In Script Editor Web Part.

Steps.

Create Custom List in SharePoint.

Created one Custom List named Customer with five Fields (Customer ID, First Name, Last Name, Location, Ph-Number) as below.

JQuery Library.

Have to use JQuery with REST API. So to include JQuery reference download JQuery library from here and upload to site Assets.

Script Editor.

Script Editor is web part provided in SharePoint 2013 for page level scripting.

How to add Script Editor Web Part.

GearBox-> Edit Page -> INSERT - > WebPart -> (In Categories) Media and Content -> (In Parts) -> Script Editor-> Add

Now Click Edit Snippet in Script Editor and start codding.

First add JQuery reference to Script Editor from Site Assests JQuery Library.

Copy URL and paste in scr.

<script src=”http://<site>/SiteAssets/jquery-1.11.3.min.js”></script>

Next step is to perform CRUD operation on Customer List.

Copy and Paste below code in Script Editor.

//Replace with your JQuery url

<script src="http://<your site name>/SiteAssets/jquery-1.11.3.min.js"></script>

<script>

var v1, v2, v3, v4, v5, itemid;

$(document).ready(function(){

 createItem();

 read();

 update();

 Deleted();

});

function read(){

var resturl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Customer')/items";

$.ajax({

url:  resturl,

        method: "GET",

        headers: { "Accept": "application/json; odata=verbose" },

        success: function (data) {

            var lnt = data.d.results.length;

             for(var i=0; i<lnt; i++ ){

              var title = data.d.results[i].Title;

              var firstname = data.d.results[i].First_x0020_Name;

              var lastname = data.d.results[i].Last_x0020_Name;

              var phnumber = data.d.results[i].Ph_x002d_Number;

               var location = data.d.results[i].Location;

                      var id = data.d.results[i].ID;

           var tbldata = "<tr><td><input type='radio' class='addcls' name='rd1'  value='"+id+"' onclick='javascript:getcheked();' /></td><td >"+title+"</td><td>"+firstname+"</td><td>"+lastname+"</td><td>"+location+"</td><td>"+phnumber+"</td></tr>"

               $("#tbl2").append(tbldata);

}

        },

        error: function (data) {

           console.log(data.responseJSON.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) {

            alert("Record Added");

        },

        error: function (error) {

           console.log(JSON.stringify(error));

        }

    });

}

function GetItemTypeForListName(name) {

 return"SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";

}

function createItem(){

$("#btn-add").click(function(){

var addNewItemUrl = "/_api/Lists/GetByTitle('Customer')/Items";

var itemType = GetItemTypeForListName('Customer');

var CustomerId = $("#CustomerId").val();

var CustomerFirstName = $("#CustomerFirstName").val();

var CustomerLastName = $("#CustomerLastName").val();

var CustomerLocation = $("#CustomerLocation").val();

var CustomerPhNumber = $("#CustomerPhNumber").val();

 var item = {

        "__metadata": { "type":  itemType },

        "Title": CustomerId,

         "First_x0020_Name": CustomerFirstName,

         "Last_x0020_Name": CustomerLastName,

          "Location": CustomerLocation,

          "Ph_x002d_Number": CustomerPhNumber

    };

 addNewItem(addNewItemUrl, item);

});

}

function update(){

$("#btndel").click(function(){

var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Customer')/getItemById(" + itemid + ")";

var itemType = GetItemTypeForListName('Customer');

var item = {

        "__metadata": { "type": itemType },

        "Title": v1,

         "First_x0020_Name": v2,

         "Last_x0020_Name": v3,

         "Location": v4,

         "Ph_x002d_Number": v5

    };

 

UpdateData(requestUri,item);

});

}

function getcheked(){

$(".addcls").each(function(){

        if($(this).is(":checked")){

                       var chkdata = $(this).val();

                                                 $("#hdndata").val(chkdata);

                                                 itemid =$("#hdndata").val();

                                                 var $row = $(this).closest("tr"),        // Finds the closest row <tr>

                         $tds2 =  $row.find("td:nth-child(2)");

                         $tds2.prop("contentEditable", "true");

                         $tds2.keyup(function(){

                             v1 = $(this).text();

                          });

                          $tds3 = $row.find("td:nth-child(3)")

                        $tds3.prop("contentEditable", "true");

                         $tds3.keyup(function(){

                         v2 = $(this).text();

                          });

                           $tds4 = $row.find("td:nth-child(4)");

                         $tds4.prop("contentEditable", "true");

                         $tds4.keyup(function(){

                             v3 = $(this).text();

                          });

                          $tds5 = $row.find("td:nth-child(5)");

                          $tds5.prop("contentEditable", "true");

                         $tds5.keyup(function(){

                             v4 = $(this).text();

                          });

                          $tds6 = $row.find("td:nth-child(6)");

                          $tds6.prop("contentEditable", "true");

                         $tds6.keyup(function(){

                             v5 = $(this).text();

                          });

                                                         }

   })

}

function UpdateData(requestUri,item){

$.ajax({

url: requestUri,

type: "POST",

data:JSON.stringify(item),

headers: {

"accept":"application/json;odata=verbose",

"content-type": "application/json;odata=verbose",

 "X-RequestDigest": $("#__REQUESTDIGEST").val(),

"X-HTTP-Method": "MERGE",

"IF-MATCH":"*"

},

success: onSuccess,     

error: onError 

});

}

function onSuccess(data) {

 alert("Updated");

}

 function onError(error) {

console.log(JSON.stringify(error));

}

 

function DeleteItem(deleteuri){

$.ajax({

url: deleteuri,

type: "POST",

headers: {

"accept":"application/json;odata=verbose",

"content-type": "application/json;odata=verbose",

 "X-RequestDigest": $("#__REQUESTDIGEST").val(),

"X-HTTP-Method": "DELETE",

"IF-MATCH":"*"

},

success: onDeleteSuccess,

error: onDeleteError

});

}

 function onDeleteSuccess(){

alert("Entry Deleted");

}

 function onDeleteError(){

console.log(JSON.stringify(error));

}

function Deleted(){

$("#btndelete").click(function(){

var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Customer')/getItemById(" + itemid + ")";

DeleteItem(requestUri);

});

}

 </script>

<div id="createData"> 

    <table> 

        <tr> 

            <td> 

                <table> 

                    <tr> 

                        <td>Customer Id</td> 

                        <td>

                            <input type="text" id="CustomerId"/> 

                        </td> 

                    </tr> 

                    <tr> 

                        <td>First Name</td> 

                        <td> 

                            <input type="text" id="CustomerFirstName"/> 

                        </td> 

                    </tr> 

                    

                    <tr> 

                        <td>Last Name</td> 

                        <td> 

                            <input type="text" id="CustomerLastName"/> 

                        </td> 

                    </tr> 

                    <tr> 

                        <td>Location</td> 

                        <td> 

                            <input type="text" id="CustomerLocation" /> 

                        </td> 

                    </tr> 

                    <tr> 

                        <td>Ph-Number</td> 

                        <td> 

                            <input type="text" id="CustomerPhNumber"/> 

                        </td> 

                    </tr> 

                    <tr> 

                        <td> 

                            <button value="Add" id="btn-add">Add</button> 

                        </td> 

                    </tr> 

                </table> 

            </td> 

        </tr> 

    </table> 

</div> 

<div id="readData">

<div id="tbldatamain">

<table id=tbl2>

<tr><th><input type="radio"></th></input><th>Customer ID</th><th>First Name</th><th>Last Name</th><th>Location</th><th>Ph-Number</th></tr>

</table>

</div>

<input type="hidden" id="hdndata" value=""/>

<div>

<table><tr><td><button id="btndel">Update</button></td><td><button id="btndelete">Delete</button></td></tr>

</div>

</div>

<style>

#readData{

position: absolute;

top: 205px;

left: 915px;

}

</style>

After pasting code Click Insert->Check In -> Publish this draft

And visit to page. Page will look like below

To Add -> Fill data and click add.

To Update -> Checked Radio button. After checked Data field will become editable. Edit field and click update.

To Delete ->  Checked Radio button and click Delete.

 

 

 

 

 


by Amir Reza via Everyone's Blog Posts - SharePoint Community

No comments:

Post a Comment