I am trying to write a JS function that sends a POST request to a SharePoint List to add new List items to that List. I have done this in the past using SP.ClientContext and would like to continue to do so, as this is the only way I know of to send multiple insert requests in a batch. Here is my code:
/**
* Inserts new items to a List
*
* @params string siteUrl
* @params object[] newListItems
* @params string listName
* @params string[] listItemFields
*
* @returns bool
**/
function insertListItems(siteUrl, newListItems, listName, listItemFields) {
if(newListItems.length == 0) {
return false;
}
var clientContext = new SP.ClientContext.get_current();
var olist = clientContext.get_web().get_lists().getByTitle(listName);
// Get SP list
var itemCreateInfo = new SP.ListItemCreationInformation();
for(var i = 0; i < newListItems.length; i++) {
oListItem = olist.addItem(itemCreateInfo);
for(var j = 0; j < listItemFields.length; j++) {
oListItem.set_item(listItemFields[j], newListItems[i][listItemFields[j]]);
}
oListItem.update();
}
clientContext.load(oListItem);
clientContext.executeQueryAsync(
this.successHandler("Items inserted to " + listName),
this.errorHandler()
);
}
I have moved this code to a new SP site, but now when I attempt to run the function I get "jQuery.Deferred exception: 'SP' is undefined ReferenceError: 'SP' is undefined" in my console. One potential issue is that this code was originally written in a SP site where the List was within the same site. Now I am working in a subsite of the SP site and the List is in a different subsite of the same SP site (not my call :/). Another potential issue is that before this was all added to a script tag within html that was embedded in the site. Now I have moved the JS out of that html file and am referring to it with an external script tag, though none of the other scripts I am using in the html file have changed.