Tuesday, 2 August 2016

CRUD Operation on List Item using REST

Refer link 1

Refer link 2

Refer Link 3

Refer Link 4

1] Add visual web part and past below HTML in that

<html>

<style>
    table {
        font-family: arial, sans-serif;
        border-collapse: collapse;
        width: 100%;
    }

    td, th {
        border: 1px solid #dddddd;
        text-align: left;
        padding: 8px;
    }

    tr:nth-child(even) {
        background-color: #dddddd;
    }
</style>

<body>

    <table>
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
        </tr>
        <tr>
            <td>
                <input type="textbox" id="fname"></td>
            <td>
                <input type="textbox" id="lname"></td>
        </tr>
        <tr>
            <td>
                <input type="button" id="btnSubmit" value="Submit"></td>
            <td>
                <input type="button" id="btnUpdate" value="Update" /></td>
        </tr>

    </table>


  
                <div id="dvListView">
                    <table id="tblCustomListData" border="1">
                        <thead>
                            <tr>
                                <th>Name
                                </th>
                                <th>Surname
                                </th>
                                <th>City
                                </th>
                                <th>Edit
                                </th>
                            </tr>
                        </thead>
                    </table>
                </div>




</body>
</html>

2] Add a page in site pages and Insert above Visual web part.

3] Create .js file and past below code in that.

<script src="http://code.jquery.com/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
 var context;
        var web;
        var Url;
        var listItemEntity;

        $(document).ready(function () {
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', FunctionReady);
                                                GetData();
            ItemSubmit();
                                                ItemUpdate();
        });


        function ItemSubmit() {
            $("#btnSubmit").click(function () {
                //reading text box values
                var firstname = $("#fname").val();
                var lastname = $("#lname").val();
                AddItemToList(listItemEntity, firstname, lastname);
            });
        }
                               
                                function ItemUpdate() {
                                                $("#btnUpdate").click(function (){
                                                 var name = $("#fname").val();
             var last = $("#lname").val();
                                                 updateItemToList(listItemEntity,name,last);
                                                });
                                }


        function FunctionReady() {
            context = new SP.ClientContext.get_current();
            web = context.get_web();
            context.load(web);
            context.executeQueryAsync(onRequestSuccess, onRequestFailure);
        }

        function onRequestSuccess() {
            Url = web.get_url();
            GetListItemEntity(Url);
        }
        function onRequestFailure(sender, args) {
            alert("Error Occured:" + args.get_message());
        }

        function GetListItemEntity(webUrl) {
            var queryUrl = webUrl + "/_api/lists/getbytitle('RestList')?$select=ListItemEntityTypeFullName";
            $.ajax({
                url: queryUrl,
                method: "GET",
                headers: { "Accept": "application/json;odata=verbose" },
                success: onEntitySuccess,
                error: onEntityFailure
            });
        }


        function onEntitySuccess(data) {
            listItemEntity = data.d.ListItemEntityTypeFullName;
        }
        function onEntityFailure(err) {
            alert(err.statusText);
        }
       
                                function GetData()
                                {
                $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('RestList')/Items?$select=Fname,Lname,City,ID&$orderby=Fname asc",      
        type: "GET",
        headers: { "accept": "application/json;odata=verbose" },
        success: successHandlerforDetails,
        error: errorHandlerforDetails
        });
        }
                               
                                function successHandlerforDetails(data) {
        var firstName='',lastName='',City='',id='',html='';
        if (data.d.results)
        {
         var object = data.d.results;
         if(object.length == 0)
         {

         }
         else
         {
           for(var i = 0; i < object.length; i++)
            {
                                                  firstName = object[i].Fname;
                                                  lastName = object[i].Lname;
                                                  City = object[i].City;
                                                  id = object[i].ID;
                                                  var trID = 'tr' + id;

                                                  html = html + "<tr id='"+ trID +"'>";
                                                  html = html + "<td>";
                                                  html = html + firstName;
                                                  html = html + "</td>";
                                                 
                                                  html = html + "<td>";
                                                  html = html + lastName;
                                                  html = html + "</td>";
                                                 
                                                  html = html + "<td style=' text-align:center'>";
                                                  html = html + "<input type='text' id= city" + id + "  class='city' value="+City+" style='width : 46px ; text-align:center'/>";
                                                  html = html + "</td>";
                                                 
                                                  html = html + "<td style=' text-align:center'>";
                                                  html = html + "<button type='button' onclick='updateClickedItem(" + id + ")'>edit</button>" + "<input type='image' src='/Style%20Library/CMR/Img/delete.png' style='height:30px;width:30px' OnClick='removeItems(" + id + ");'>";
                                                  html = html + "</td>";
                                                  html = html + "</tr>";

                                                }
                                 }
                                }

                                 $('#tblCustomListData').append(html);
                                }

                                function errorHandlerforDetails(args,sender) {
                                                alert('Failed');
                                }
                               
        function AddItemToList(r, firstname, colValue) {
            try {

                var queryUrl = Url + "/_api/lists/GetByTitle('RestList')/items";

                $.ajax({
                    url: queryUrl,
                    type: "POST",
                    contentType: "application/json;odata=verbose",
                    data: JSON.stringify(
                        {
                            '__metadata': {
                                'type': r
                            },
                            'Fname': firstname,
                            'Lname': colValue
                        }),
                    headers: {
                        "accept": "application/json;odata=verbose",
                        "X-RequestDigest": $("#__REQUESTDIGEST").val()
                    }, success: onQuerySucess,
                    error: onQueryFailure
                });
            }
            catch (ex) {
                alert("Exception" + ex.message);
            }
        }

        function onQuerySucess() {
            alert('Item Added Successfully');
        }

        function onQueryFailure(error) {
            //alert("Failure:"+error.status+","+error.statusText);
            alert(JSON.stringify(error));
        }
                               
                                function updateItemToList(a,fname,lname)
                                {
                                                try{
                                                                var updateQueryUrl= Url + "/_api/lists/GetByTitle('RestList')/items(1)";
                                                               
                                                                $.ajax({
              url: updateQueryUrl,
              type: "POST",
              data: JSON.stringify(
                                                         {
                        '__metadata': {'type': a },
                        'Fname': fname,
                        'Lname': lname
                     }),
              headers: {
                               "Accept": "application/json;odata=verbose",
                               "content-type": "application/json; odata=verbose",
                               "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                               "X-HTTP-Method": "MERGE",
                               "If-Match": "*"
                            },success: onQuerySucessUpdate,
                              error: onQueryFailureUpdate
                                                                                 });
                                                }
                                                 catch (ex) {
                alert("Exception" + ex.message);
            }
                                }
                               
                                function onQuerySucessUpdate() {
            alert('Item Updated Successfully');
        }
                               
                                function onQueryFailureUpdate(error) {
            //alert("Failure:"+error.status+","+error.statusText);
            alert(JSON.stringify(error));
        }
                               
                                function updateClickedItem(id)
                                {
                                                var itemcity = $("#city" + id + "").val();
                                                updateclickItemtoList(listItemEntity,itemcity,id);
                                }
                                function updateclickItemtoList(metadataType,city,Itemid)
                                {
                                                try{
                                                                var updateQueryUrl= Url + "/_api/lists/GetByTitle('RestList')/items("+Itemid+")";
                                                               
                                                                $.ajax({
              url: updateQueryUrl,
              type: "POST",
              data: JSON.stringify(
                                                         {
                        '__metadata': {'type': metadataType },
                        'City': city
                     }),
              headers: {
                               "Accept": "application/json;odata=verbose",
                               "content-type": "application/json; odata=verbose",
                               "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                               "X-HTTP-Method": "MERGE",
                               "If-Match": "*"
                            },success: onQuerySucessUpdate,
                              error: onQueryFailureUpdate
                                                                                 });
                                                }
                                                 catch (ex) {
                alert("Exception" + ex.message);
            }
                                }
                               
                                function removeItems(Itmid)
                                {
                                                deleteListItem(listItemEntity,Itmid);
                                }
                                function deleteListItem(metadataType,Itemid)
                                {
                                                try{
                                                                var updateQueryUrl= Url + "/_api/lists/GetByTitle('RestList')/items("+Itemid+")";
                                                               
                                                                $.ajax({
              url: updateQueryUrl,
              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: onQuerySucessDelete,
                              error: onQueryFailureDelete
                                                                                 });
                                                }
                                                 catch (ex) {
                alert("Exception" + ex.message);
            }
                                }
                                function onQuerySucessDelete() {
            alert('Item Deleted Successfully');
        }
                               
                                function onQueryFailureDelete(error) {
            //alert("Failure:"+error.status+","+error.statusText);
            alert(JSON.stringify(error));
        }

</script>


4] Refer above .js file in CEWP where we added visual web part.


1 comment: