I am trying to create a new choice (radio buttons) field using REST API request in my SharePoint Online environment and this is the code I'm using:
$.ajax({
url: "https://mydomain.sharepoint.com/sites/mysite/mysubsite/_api/contextinfo",
method: "POST",
headers: { "Accept": "application/json; odata=verbose" },
success:function(data){
var digest = data.d.GetContextWebInformation.FormDigestValue;
$.ajax({
url: "https://mydomain.sharepoint.com/sites/mysite/mysubsite/_api/web/lists/GetByTitle('MyListName')/fields",
type: "POST",
data: { '__metadata': { 'type': 'SP.FieldChoice' }, 'FieldTypeKind': 6, 'Title': 'NewChoiceField', 'Choices': { '__metadata': { 'type': 'Collection(Edm.String)' }, 'results': [ 'Choice 1', 'Choice 2', 'Choice 3' ] }, 'EditFormat': 1 },
headers: {
"X-RequestDigest": $('#__REQUESTDIGEST').val(digest),
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: function(){console.log("success");},
error: function(){console.log("error");}
});
},
error:function(data){
console.log("error getting the digest value")
}
});
However, I get '403 Forbidden' as a response.
The Microsoft.SharePoint.SPException
thrown is
"The security validation for this page is invalid and might be corrupted. Please use your web browser's Back button to try your operation again."
Any ideas?
P.S. The account has definitely got the required permissions.
"X-RequestDigest": $('#__REQUESTDIGEST').val
and check. If its in the same web, you dont needcontextInfo
value via AJAX call$('#__REQUESTDIGEST').val()
is undefined in modern SharePoint pages, hence the first request to get the digest.