Wednesday, May 13, 2020

How we can update the item using Rest Api. Write complete syntax and explain each line?


Ans:-function UpdateListItemUsingItemId(Id) {
    $.ajax
        ({ 
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('list name')/items(" + Id + ")",
            type: "POST",
            headers:
            {   
               // Accept header: Specifies the format for response data from the server.         
          "Accept": "application/json;odata=verbose",
                //Content-Type header: Specifies the format of the data that the client is sending to the server,
               // odata: is the standard.
               //verbose: you’ll get the maximum amount of information about the data coming from or going to server.
        "Content-Type": "application/json;odata=verbose",
                // IF-MATCH header: Provides a way to verify that the object being changed has not been  changed since it was last retrieved.
       // "IF-MATCH":"*", will overwrite any modification in the object, since it was last retrieved.
                // Here we are going to compare the Etag value of the retrieved item (stored in Hidden Field) to the Etag value of the same item which we are going to update
                "IF-MATCH": document.getElementById("hiddenField").value,
                //X-HTTP-Method: The MERGE method updates only the properties of the entity , while the PUT method replaces the existing entity with a new one that                       you supply in the body of  the POST
       "X-HTTP-Method": "MERGE",
                // X-RequestDigest header: When you send a POST request, it must include the form digest value in X-RequestDigest header. This digest proves validity of                     your request to SharePoint. Because this token is valid by only for a limited period of time of by default 30 minutes.you have to ensure that the token you                         have is valid before adding it to your request or the request fails.
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
            data: JSON.stringify({
                __metadata:
                {
                    // Format of the "type" is: SP.Data.<>ListItem. First character of the <> should be in Capital
                    type: "SP.Data.List_x0020_NameListItem"
                },
                Description: "Updated Description"
            }),
            success: function (data, status, xhr) {
                console.log("Success");
            },
            error: function (xhr, status, error) {
                console.log("Failed");
            }
        });
}
UpdateListItemUsingItemId(Id);

No comments:

Post a Comment