2

I have used the below mentioned approach to update multiple items in SharePoint 2010 list,

How to update list items using JavaScript Object Model in SP 2013

How to update multiple items in sharepoint list online using javascript

How to update multiple items in sharepoint list online using javascript

Now, i have to update multiple items in SharePoint 2013 list on my Addon. I am using the SP.RequestExecutor.js to update the single item like this,

executor.executeAsync({
    url: appweburl +
    "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + listTitle + "')/items(1)?@target='" +
    hostweburl + "'",
    method: "POST",
    body: JSON.stringify({
        "__metadata": res.__metadata,
        Title: res.Title
    }),
    headers: {
        "Accept": "application/json;odata=verbose",
        "Content-Type": "application/json;odata=verbose",
        "X-HTTP-Method": "MERGE",
        "IF-MATCH": "*"
    },
    success: function (data) {
        if (onsuccess && typeof onsuccess == "function")
            onsuccess(data);
        console.log(JSON.stringify(data));
    },
    error: function (data, errorCode, errorMessage) {
        if (onfailure && typeof onfailure == "function")
            onfailure(data, errorCode, errorMessage);
        console.log(JSON.stringify(err));
    }
});

How to update multiple sharepoint list items on SP 2013 Addon?

1

You can insert items in batch using REST API. The following helper methods will be used.

Helper method to insert items in batch using REST API

function addItemsBatch(weburl, items, listTitle, success, fail) {

  // generate a batch boundary
  var batchGuid = generateGUID();

  // creating the body
  var batchContents = new Array();
  var changeSetId = generateGUID();

  // for each item...
  for (var index = 0; index < items.length; index++) {

    var item = items[index];
    var endpoint = weburl
                   + "/_api/web/lists/getbytitle('" + listTitle + "')"
                   + "/items";

    // create the changeset
    batchContents.push('--changeset_' + changeSetId);
    batchContents.push('Content-Type: application/http');
    batchContents.push('Content-Transfer-Encoding: binary');
    batchContents.push('');
    batchContents.push('POST ' + endpoint + ' HTTP/1.1');
    batchContents.push('Content-Type: application/json;odata=verbose');
    batchContents.push('');
    batchContents.push(JSON.stringify(item));
    batchContents.push('');
  }
  // END changeset to create data
  batchContents.push('--changeset_' + changeSetId + '--');


  // generate the body of the batch
  var batchBody = batchContents.join('\r\n');

  // start with a clean array
  batchContents = new Array();

  // create batch for creating items
  batchContents.push('--batch_' + batchGuid);
  batchContents.push('Content-Type: multipart/mixed; boundary="changeset_' + changeSetId + '"');
  batchContents.push('Content-Length: ' + batchBody.length);
  batchContents.push('Content-Transfer-Encoding: binary');
  batchContents.push('');
  batchContents.push(batchBody);
  batchContents.push('');
  //bath end
  batchContents.push('--batch_' + batchGuid);

  batchBody = batchContents.join('\r\n');

  // create the request endpoint 
  var endpoint = weburl + '/_api/$batch';

  // batches need a specific header
  var batchRequestHeader = {
    'X-RequestDigest': $("#__REQUESTDIGEST").val(),
    'Content-Type': 'multipart/mixed; boundary="batch_' + batchGuid + '"'
  };

  // create request
  $.ajax({
    url: endpoint,
    type: 'POST',
    headers: batchRequestHeader,
    data: batchBody,
    success: function (response) {
      success();
    },
    fail: function (error) {
      fail(error);
    }
  });
}

Helper method to generate random GUID for batch request

function generateGUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = (d + Math.random() * 16) % 16 | 0;
      d = Math.floor(d / 16);
      return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
    });
    return uuid;
}

Method to get the SP List Item Entity Name

function getItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}

Calling method to insert items

function addItems() {
    var listType = getItemTypeForListName("listTitle");
    var objItems = [
            {
                __metadata: {
                    type: listType
                },
                Title: "test1"
            },
            {
                __metadata: {
                    type: listType
                },
                Title: "test2"
            }];
    addItemsBatch(_spPageContextInfo.webAbsoluteUrl, objItems, "listTitle", function() {
        alert('success');
    }, function(error) {
        alet('failed');
    });
}
0

I will guide you to update multiple items in a SP List without hassle. I have done this many times and updated hundreds of List items in just matter of seconds. You can use SPServices.JS to do this. First you need to form your update string using for loop based on your requirement. Below is the sample code:

var itemIDArrayUpdate = [,];    
    //run some loop and prepare all data to be updated
    // I am simply showing demo for let say 10 items    
        for(var k=0; k<10; k++){
            itemIDArrayUpdate.push(["xx"+k.toString(),"yy"+k.toString(),"zz"+k.toString(),]);
        }
        // I repeat, above array is just a sample. you have write your own logic to make collection of data updates


    var update_string = "<Batch OnError='Continue'>";           
        for(var i=0; i<itemIDArrayUpdate.length; i++ )
        {
            update_string = update_string + "<Method ID='" + i + "' Cmd='Update'>" +
                "<Field Name='Field_0'>" + itemIDArrayUpdate[i][0] + "</Field>" +
                "<Field Name='Field_1'>" + itemIDArrayUpdate[i][1] + "</Field>" +    
                "<Field Name='Field_2'>" + itemIDArrayUpdate[i][2] + "</Field>" +                       
                "</Method>";

        }
        update_string = update_string + "</Batch>";        

        // apply batch to update list items

        $().SPServices({
            operation: "UpdateListItems",
            async: false,
            batchCmd: "Update",
            listName: "your_list_name",
            webURL:"https://your_tenant/sites/your_site_name",
            updates: update_string,
            completefunc: function(xData, Status) {
              if (xData.status == 200) {
                   alert("Updated Successfully");
                    location.reload();
                } else {
                    alert(xData.responseXML.xml);
                }                   
                }
        });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.