Before the question I want to give some background as I feel the problem here could stem from anywhere. On our SharePoint site, we have a page with a button that an html file stored in the sites document library. That file has a JavaScript file associated with it also stored in the document library. Together the files provide users with a data entry interface. Ideally, once the user submits the form, the JavaScript creates a new item in one of the lists on the SharePoint site. Below is a test snippet of the code that runs after submission.
function createItemInSharePointList(survey) {
try {
// Ensure SP.ClientContext is defined
if (typeof SP === 'undefined' || typeof SP.ClientContext === 'undefined') {
console.error("SharePoint scripts not loaded.");
return;
}
// Get the current SharePoint context
var context = SP.ClientContext.get_current();
// Get the target list
var list = context.get_web().get_lists().getByTitle("Test List");
// Create a new list item
var itemCreateInfo = new SP.ListItemCreationInformation();
var newItem = list.addItem(itemCreateInfo);
// Set the field values for the new item
newItem.set_item("Item 1", survey.data.firstQ);
newItem.set_item("Item 2", survey.data.secondQ);
newItem.set_item("Item 3", survey.data.thirdQ);
// Save the changes
newItem.update();
context.load(newItem);
// Execute the request
context.executeQueryAsync(
function () {
console.log("Item created successfully!");
},
function (sender, args) {
console.error("Error creating item: " + args.get_message());
}
);
} catch (error) {
console.error("Error creating item in SharePoint list:", error);
}
}
Now for the problem. When the user submits the form, an error is thrown that “SP.ClientContext is not defined.” Initially I thought the issue was that the SP.js library wasn’t loaded, but after placing some checks in the html that doesn’t appear to be the case. The code below prints that everything has been loaded successfully except SP.ClientContext.
<!-- Add references to the SharePoint JSOM libraries -->
<script type="text/javascript" src="<the-sharepoint-site-goes-here>/_layouts/15/sp.runtime.js" onload="console.log('sp.runtime.js loaded successfully');" onerror="console.error('Failed to load sp.runtime.js');"></script>
<script type="text/javascript" src="<the-sharepoint-site-goes-here>/_layouts/15/sp.js" onload="console.log('sp.js loaded successfully');" onerror="console.error('Failed to load sp.js');"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
console.log('Document fully loaded and parsed');
if (typeof SP !== 'undefined' && SP.ClientContext) {
console.log('SP.ClientContext is defined');
} else {
console.error('SP.ClientContext is not defined');
}
});
</script>
This code was created by a coworker and not myself, so as a result I’m not certain the way it has been done is even correct. I’m not sure if this makes a difference but the SharePoint site is on-prem. Any guidance for how to fix this would be great.