0

I have tried to create multiple list items in sharepoint online using rest, I am getting the success message but still the items are not created in the list.

Below is the code:-

function CreateIdea(){
      var EmployeesAsJson = [
            {
                __metadata: {
                    type: 'SP.Data.IdeaEngineListItem'
                },
                Title: 'User1'
            },
            {
                __metadata: {
                    type: 'SP.Data.IdeaEngineListItem'
                },
                Title: 'User2'
            },
            {
                 __metadata: {
                     type: 'SP.Data.IdeaEngineListItem'
                 },
                 Title: 'User3'
             }
      ];             


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

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

        // get current host
        var temp = document.createElement('a');
        temp.href = _spPageContextInfo.webAbsoluteUrl;
        var host = temp.hostname;

        // for each employee...
        for (var employeeIndex = 0; employeeIndex < EmployeesAsJson.length; employeeIndex++) {

            var employee = EmployeesAsJson[employeeIndex];

            // create the request endpoint
            var endpoint = _spPageContextInfo.webAbsoluteUrl
                           + '/_api/web/lists/getbytitle(\'IdeaEngine\')'
                           + '/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(employee));
            batchContents.push('');
        }
        // END changeset to create data
        batchContents.push('--changeset_' + changeSetId + '--');

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

        // create the request endpoint 
        var endpoint = _spPageContextInfo.webAbsoluteUrl
                       + '/_api/$batch';

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

        // create request
        jQuery.ajax({
            url: endpoint,
            type: 'POST',
            headers: batchRequestHeader,
            data: batchBody,
            success: function (response) {
                alert("Successfully saved a batch request");
                SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel);
            },
            fail: function (error) {
                alert('.. create employee FAIL ', error);
                SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel);
            }
        });
}

/*
    * @name generateUUID
    * @description
    * Generates a GUID-like string, used in OData HTTP batches.
    * 
    * @returns {string} - A GUID-like string.
    */
function generateUUID() {
    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;
};

Please help me know where is the issue in the code. I have referred the post [https://www.codeproject.com/Tips/878531/Save-Mutiple-records-to-SharePoint-using-REST-API]

0

First of all you need to specify start and end of batch in body

--batch_someguid
body
--batch_someguid--

Secondly, a changeset must start with the batch boundary and include some specific lines describing the actual changeset.
For e.g. as below

--batch_someguid
Content-Type: multipart/mixed; boundary="changeset_guid"
Host: [your-sponline-domain]
Content-Length: [size in bytes of the changeset]
Content-Transfer-Encoding: binary

You can follow this post from Andrew Connell to understand batch request properly

Modified code is as below

function CreateIdea(){
  var EmployeesAsJson = [
        {
            __metadata: {
                type: 'SP.Data.IdeaEngineListItem'
            },
            Title: 'User1'
        },
        {
            __metadata: {
                type: 'SP.Data.IdeaEngineListItem'
            },
            Title: 'User2'
        },
        {
             __metadata: {
                 type: 'SP.Data.IdeaEngineListItem'
             },
             Title: 'User3'
         }
  ];             


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

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

    // get current host
    var temp = document.createElement('a');
    temp.href = _spPageContextInfo.webAbsoluteUrl;
    var host = temp.hostname;

    batchContents.push('--batch_' + batchGuid);
    batchContents.push('Content-Type: multipart/mixed; boundary="changeset_' + changeSetId + '"');
    batchContents.push('Content-Transfer-Encoding: binary');
    batchContents.push(''); //NECESSARY LINE SPACE

    // for each employee...
    for (var employeeIndex = 0; employeeIndex < EmployeesAsJson.length; employeeIndex++) {

        var employee = EmployeesAsJson[employeeIndex];

        // create the request endpoint
        var endpoint = _spPageContextInfo.webAbsoluteUrl
                       + '/_api/web/lists/getbytitle(\'IdeaEngine\')'
                       + '/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(employee));
        batchContents.push('');
    }
    // END changeset to create data
    batchContents.push('--changeset_' + changeSetId + '--');
    batchContents.push('--batch_' + batchGuid + '--');  //END OF BATCH

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

    // create the request endpoint 
    var endpoint = _spPageContextInfo.webAbsoluteUrl
                   + '/_api/$batch';

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

    // create request
    jQuery.ajax({
        url: endpoint,
        type: 'POST',
        headers: batchRequestHeader,
        data: batchBody,
        success: function (response) {
            alert("Successfully saved a batch request");
            SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel);
        },
        fail: function (error) {
            alert('.. create employee FAIL ', error);
            SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel);
        }
    });
  }

  function generateUUID() {
   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;
 };
| improve this answer | |
  • How can we get the list items from multiple lists using batch REST API? – Pratik Hajare Jan 10 '19 at 13:01

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.