I'm having a problems using REST to POST to a SharePoint List named Employees.
I can get my code to GET data from the list, but when I try to POST data to the list it does not work. It gives me an 403 (FORBIDDEN) error:
POST https://company.sharepoint.com/sites/siteName/_api/web/lists/getbytitle('Employees')/items 403 (FORBIDDEN)
Here is the code I use to GET and POST
Get List Items
function GetListItemsFromSPList() {
var siteUrl = "https://company.sharepoint.com/sites/siteName/";
$('#listitems').empty();
$.ajax({
url: siteUrl + "_api/web/lists/getbytitle('Employees')/items/",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var listItems = data.d.results;
listItems.forEach(function (entry) {
var node = document.createElement("LI");
var textnode = document.createTextNode(entry.UserID);
node.appendChild(textnode);
document.getElementById("listitems").appendChild(node);
});
},
error: function (data) {
alert("Error: " + data)
}
});}
Add List Items
function AddListItem() {
var siteUrl = "https://company.sharepoint.com/sites/siteName/";
$.ajax
({
url: siteUrl + "_api/web/lists/GetByTitle('Employees')/items",
type: "POST",
data: JSON.stringify
({
'__metadata':{'type': 'SP.Data.EmployeesListItem'},
'UserID': 'US-USERID',
'Position': 'Position Name'
}),
headers:
{
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "POST"
},
success: function(data, status, xhr)
{
GetListItemsFromSPList();
},
error: function(xhr, status, error)
{
alert("Error");
}
});}
I'm new to using REST, so I'm not sure if I have left anything out. Please let me know if you see anything I have left out, have any advice on where to start, or if you have any knowledge on this problem.
EDIT:
So I have made changes to my code to reflect the suggestions made by max fuller and Luke Walker in the answers below; however, this did not fix my problem with the 403 (FORBIDDEN) error.
I logged the Form Digest Value to the console with console.log($("#__REQUESTDIGEST").val()); and it returned a value of undefined, so this is potentially my problem. Is there some step that I must do before my create code to get this to work correctly?