Monday, October 30, 2017

SharePoint List item CRUD (REST) operation


SharePoint List item CRUD (REST) operation 


Step1: Create a Custom List name it as "MyList". remove quotes and Create a multiline column "Name".
       1.1: Create a SharePoint Page:

Step2: Edit page from one of these two options:
 

Step3: Select insert and click on Webpart,
            From Categories select Media and Content then Choose Script Editor and click on ok to add Webpart.

Select Edit snippet copy below code and past in Snippet area and click on insert and save the page.


<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>

<div>
    <table>
        <tr>
            <td>
                <label >Title:</label>
            </td>
            <td>
                <input type="text" id="txtTitle" />
            </td>
        </tr>
         <tr>
            <td>
                <label >Name:</label>
            </td>
            <td>
                 <input type="text" id="txtName" />
            </td>
        </tr>
         <tr>
            <td>
              
            </td>
            <td>
                <input type="button" value="Reset" onclick="ResetForm();" />
                 <input type="button" id="UpdateOrCreate" Value="Create Item" onclick="RenameORUpdateOrCreateItem();"/>
            </td>
        </tr>
    </table>


    <div id="divShowItems"></div>


</div>

<script>
    var UpdateItemID = 0;
    var listName = "MyList";
    $(document).ready(function () {      
         Read_and_Bind_ListItems();
    });

    function RenameORUpdateOrCreateItem() {
        if ($("#txtTitle").val() != "") {
          //  var listName = "MyList";
            var valItemTitle = $("#txtTitle").val();
            // Create New Item
            if ($("#UpdateOrCreate").val() =="Create Item")
                AddListItem(listName, _spPageContextInfo.webAbsoluteUrl, valItemTitle, function () {
                    Bind_and_Reset_Form();
                alert("New Item has been created successfully.");
            }, function () {
                alert("Ooops..! an error occured. Please try again.");
            });
            else
            {// Rename
                Update(listName);             
            }
        }
        else {
            alert('Please enter Title');
            //reset its value after update
          
        }
        // success: The function to execute if the call is sucesfull, failure: The function to execute if the call fails
        function AddListItem(listName, webUrl, newItemTitle, success, failure) {
            //var itemType = "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
            var itemType = "SP.Data." + listName + "ListItem";
          
            var addItemMetaData = {
                "__metadata": { "type": itemType },
                "Title": newItemTitle,
                "Name": $("#txtName").val()
            };

            $.ajax({
                url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
                type: "POST",
                contentType: "application/json;odata=verbose",
                data: JSON.stringify(addItemMetaData),
                headers: {
                    "Accept": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val()
                },
                success: function (data) {
                    success(data);                  
                },
                error: function (data) {
                    failure(data);
                }
            });
        }        
    }

  
    function  Read_and_Bind_ListItems() {
       // var listName = "MyList";
        var url = _spPageContextInfo.webAbsoluteUrl;

        getListItems(listName, url, function (data) {
            var items = data.d.results;
            var listItemsdata = '<div> <table border="1">';
            listItemsdata += '<tr style="background-color: #87b586">  <th>Title </th> <th>Name </th> <th>Actions</th> </tr>'
            for (var i = 0; i < items.length; i++) {
                listItemsdata += '<tr><td> <lable class="itemTitle">' + items[i].Title +
                    '</label></td> <td> <lable class="itemName">' + items[i].Name + '</label></td><td>'
                    + '<input type="button" Id="' + items[i].ID + '" value="Edit" class="renameDeleteAnItem" /> <input type="button" Id="' + items[i].ID + '" value="Delete" class="renameDeleteAnItem" /> </td> </tr>';
              }
            listItemsdata += '</table></div>';
          
            $("#divShowItems").empty()
            $("#divShowItems").append(listItemsdata);

        }, function (data) {
            alert("Ooops, an error occured. Please try again");
        });
    }
    //Read or get- All Items from a List
    function getListItems(listName, siteurl, success, failure) {
        $.ajax({
            url: siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items",
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    }

    // Get Current Row Item while clicking on Rename
    $(document).on("click", ".renameDeleteAnItem", function () {
     
        var btnType = $(this).attr("value");
        if (btnType == "Edit") {
            UpdateItemID = $(this).attr("Id");
            $("#txtTitle").val($(this).closest('tr').find('.itemTitle').text());
            $("#txtName").val($(this).closest('tr').find('.itemName').text());
            $("#UpdateOrCreate").val("Update!");
        }
        else if (btnType == "Delete") {         
          //  var listName = "MyList";
            var url = _spPageContextInfo.webAbsoluteUrl;
            var itemId = $(this).attr("Id");          
            deleteListItem(itemId, listName, url, function () {
                Bind_and_Reset_Form();
                alert("Item deleted successfully");
            }, function () {
                alert("Ooops, an error occured. Please try again");
            });
            Bind_and_Reset_Form();
        }
      
    });
   

    // Update edited Item  
    function Update(listName) {       
        var url = _spPageContextInfo.webAbsoluteUrl;
        var itemId = UpdateItemID;
        var title = $("#txtTitle").val();
        var NameFld = $("#txtName").val();      
        updateListItem(itemId, listName, url, title,NameFld, function () {
            Bind_and_Reset_Form();
            alert("Item updated..!");
        }, function () {
            alert("Ooops, an error occured. Please try again");
        });
    }

    function updateListItem(itemId, listName, siteUrl, title, NameFld, success, failure) {
         var itemType =  "SP.Data." + listName + "ListItem";

        var item = {
            "__metadata": { "type": itemType },
            "Title": title,
            "Name": NameFld
        };
       
        getListItemWithId(itemId, listName, siteUrl, function (data) {
            $.ajax({
                url: data.__metadata.uri,
                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": data.__metadata.etag
                },
                success: function (data) {
                    success(data);
                },
                error: function (data) {
                    failure(data);
                }
            });
        }, function (data) {
            failure(data);
        });
    }
    function getListItemWithId(itemId, listName, siteurl, success, failure) {
        var url = siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?$filter=Id eq " + itemId;
        $.ajax({
            url: url,
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: function (data) {
                if (data.d.results.length == 1) {
                    success(data.d.results[0]);
                }
                else {
                    failure("Multiple results obtained for the specified Id :" + itemId + " value");
                }
            },
            error: function (data) {
                failure(data);
            }
        });
    }

    function deleteListItem(itemId, listName, siteUrl, success, failure) {
        getListItemWithId(itemId, listName, siteUrl, function (data) {
            $.ajax({
                url: data.__metadata.uri,
                type: "POST",
                headers: {
                    "Accept": "application/json;odata=verbose",
                    "X-Http-Method": "DELETE",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "If-Match": data.__metadata.etag
                },
                success: function (data) {
                    success(data);
                },
                error: function (data) {
                    failure(data);
                }
            });
        },
       function (data) {
           failure(data);
       });
    }



    function ResetForm() {
        $("#UpdateOrCreate").val("Create Item");
        $("#txtTitle").val("");
        $("#txtName").val("");
        UpdateItemID = 0;
    }

    function Bind_and_Reset_Form() {
        ResetForm();
        Read_and_Bind_ListItems();
    }

</script>