1

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?

  • @max fuller I made the changes, but it didn't seem to work. I'm sure that it would have caused problems down the line, but the 403 persists because of some other problem – JacobCaldwell Aug 17 '17 at 14:23
  • @Luke Walker I tried the suggested code change to no avail. As mentioned I used the console to check the formdigestvalue and it return undefined. – JacobCaldwell Aug 17 '17 at 14:26
  • is this a sharepoint hosted app ? are you trying in the same site collection or different site collection ? Also do you have rights to add item , can you check manually ? – Gautam Sheth Aug 17 '17 at 14:26
  • @GautamSheth It is not a hosted app, it is within the same site collection, and I should have add rights since I have full control permissions. – JacobCaldwell Aug 17 '17 at 14:32
0

First console the formdigestvalue at the start of your create function, (make sure the value is valid prior to making the call, as if this is not present you won't be able to progress and will error out automatically)

In your function to create a new list item, prior to making the ajax call store your "List item" in a variable.

for example:

var item = {
'__metadata': { 'type': 'SP.P.Data.EmployeesListItem'},
'UserID': 'US-USERID',
'Position' : "Position Name",
}

then, pass your item to the data section of the ajax call:

data: JSON.stringify(item)

(better practice as opposed to hard coding into the ajax call)

Hope this helps!

0

Try these updates to the data section.

data: JSON.stringify
({
    '__metadata':{'type':'SP.Data.EmployeesListItem'},
                 'UserID': 'US-USERID',
                 'Position': 'Position Name'
}),

Couple of potential fixes for undefined form digest. Im not sure how your page is setup however there should be a formdigest somewhere in your page. if the value is null maybe this is missing?

<form runat="server">
   <SharePoint:FormDigest ID="FormDigest1" runat="server">
</SharePoint:FormDigest>
</form>

Alternatively you could use an API call to gain a formdigest value and use that in your header as per below.

function getFormDigest(webUrl) {
    return $.ajax({
        url: webUrl + "/_api/contextinfo",
        method: "POST",
        headers: { "Accept": "application/json; odata=verbose" }
    });
}

"X-RequestDigest": data.d.GetContextWebInformation.FormDigestValue

Credit where due i took this from an answer Vadim Gremyachev provided to the question here https://stackoverflow.com/questions/32435432/sharepoint-2013-via-rest-api-error-403-forbidden-when-trying-to-create-item

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.