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');
});
}