1

Trying to create my first web part for SharePoint online that writes to a list. But when I do a post using jQuery ajax I receive an Unauthorized error. Any help you be greatly appreciated.

I am reusing some found code so maybe I'm missing something:

I first get the form digest:

var formDigest;       

$.ajax({
          async: false,
          url: "https://#################/_api/contextinfo",
          type: "POST",
          headers: {
            "accept": "application/json;odata=verbose",
            "contentType": "text/xml"
          },
          success: function (data) {
            debugger;
            var requestdigest = data;
            formDigest = data.d.GetContextWebInformation.FormDigestValue;
          },
          error: function (err) {
            debugger;
            alert(err.statusText);
            console.log(JSON.stringify(err));
          }
        });

Then I try to post to the list:

$.ajax({  
              async: false,                   
              url: "https://#################/_api/web/lists/getByTitle('TestList')/items",  
              method: "POST", 
              data: JSON.stringify({  
                  '__metadata': {  
                      'type': 'SP.Data.TestListListItem'
                  },  
                  'Title': "TEST"
              }),  
              headers: {  
                "Accept": "application/json;odata=verbose",
                "Content-Type": "application/json;odata=verbose",
                "X-RequestDigest": formDigest,
                "X-HTTP-Method": "POST",
                "X-FORMS_BASED_AUTH_ACCEPTED": "f"
              },  
              success: function(data) {      
                  alert("Item created successfully");
              },  
              error: function(error) {      
                  console.log(JSON.stringify(error));              
              }  
        
          });

When I try to do the insert I get a Unauthorized error.

Now I am able to do a get to the list but when I do a POST the error occurs.

2
  • Do you have at least contribute/edit permissions on SharePoint list? Are you able to create/update list items from UI/browser? Also, are you trying to create a new item or update existing list item? Aug 26, 2021 at 9:17
  • Did you try without the X-HTTP-Method and X-FORMS_BASED_AUTH_ACCEPTED headers? I've never used those headers when doing a POST to create an item. I do use X-HTTP-Method when doing a POST to update an existing item, but it doesn't look like that's what you are doing there. Aug 26, 2021 at 17:17

1 Answer 1

0

If you are trying to create a new list item in SharePoint list, use below code:

function CreateListItem() {
    $.ajax
        ({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('TestList')/items",
            type: "POST",
            headers:
            {
                "Accept": "application/json;odata=verbose",
                "Content-Type": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
            data: JSON.stringify
            ({
                __metadata:
                {
                    type: "SP.Data.TestListListItem"
                },
                Title: "TEST"
            }),
            success: function (data, status, xhr) {
                console.log("Success");
            },
            error: function (xhr, status, error) {
                console.log("Failed");
            }
        });
}

Source: Create List Item in SharePoint using REST API

You can find more similar examples at: Adding new list item using REST

Microsoft official Docs: Working with list items by using REST


More information about permissions on SharePoint lists: Customize permissions for a SharePoint list or library

4
  • There does not seem to be any difference between this code and my code above. They both produce the same 401 error.
    – FenrirZA
    Aug 26, 2021 at 9:36
  • Is there a setting in Sharepoint that I need to change to enable Post messages ?
    – FenrirZA
    Aug 26, 2021 at 9:37
  • You need to grant yourself at contribute/edit permissions on SharePoint list. check this. Aug 26, 2021 at 10:13
  • I am the owner of the list. I am able to make a post using spHttpClient.
    – FenrirZA
    Aug 26, 2021 at 10:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.