AnsweredAssumed Answered

How to update SharePoint List Item from Task Form using Javascript

Question asked by jatinchandra on Jun 17, 2018

Hello Everyone,

 

I'm using Nintex for Office365. I have a requirement wherein, I've to update a SharePoint list item present in Host Web using Javascript from a Task Form. I was able to Read the list items using Javascript. But not able to update them. Below is the code I'm using to update the List Item. Please let me know where I'm doing a mistake.

 

NWF$(document).ready(function () {

   updateItem();

});

function updateItem() {
   var hostweburl = decodeURIComponent(Utils.getQueryStringParameter('SPHostUrl'));
   var appweburl = decodeURIComponent(Utils.getQueryStringParameter('SPAppWebUrl'));
   var taskID = 2;
   var listName = "NWFTest"; 
   var context = new SP.ClientContext(appweburl);
   var factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
   context.set_webRequestExecutorFactory(factory);
   var appContextSite = new SP.AppContextSite(context, hostweburl);
   NWF$.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js").done(function (script, textStatus) {
      executeCrossDomainRequest(appweburl, listName, taskID, hostweburl)
   }).fail(function (jqxhr, settings, exception) {
      alert("Script failed to load. Some of the functionalities may not work. Please report the error to the administrator")
   });
}

function executeCrossDomainRequest(appweburl, listName, taskID, hostweburl) {
   var executor = new SP.RequestExecutor(appweburl);
   var url = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + listName + "')/items('" + taskID +    "')?    @target='" + encodeURIComponent(hostweburl) + "'";
   var metaData = {
      __metadata: { 'type': 'SP.Data.NWFTestListItem' },
      Title: 'TestUpdate'
   };
   executor.executeAsync({
      url: url,
      method: "POST",
      headers: {
         "Accept": "application/json; odata=verbose",
         "content-type": "application/json; odata=verbose",
         "X-HTTP-Method": "MERGE",
         "IF-MATCH": "*"
      },
   body: JSON.stringify(metaData),
   success: function (data) {
      alert("Update Item Success: " + JSON.stringify(data));
   },
   error: function (err) {
   alert("Update Item Error: " + JSON.stringify(err));
   },
});
}

 

 

In the above code, I'm using a function "getQueryStringParameter" to get the values of appweburl, hostweburl etc., which are working perfectly fine.
What I want to achieve is, to update the List Item of List "NWFTest" with title "TestUpdate". For test purpose, I've hardcoded the ListItem ID as "2". Most of the times the code shows success alert/goes into success block, but it doesn't update the list item.

Outcomes