REST API couldn't create list field
-
26-01-2021 - |
Question
I am trying to create list fields using REST api. But when I call the code given below many times, it creates some of the fields and not all of them.
code:
function addnewfield(name){
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/Lists/getbytitle('Flight')/fields",
type: "POST",
data: JSON.stringify({ '__metadata': { 'type': 'SP.FieldText' }, 'Title':''+name+'', 'FieldTypeKind': 2,"StaticName": ""+name+"" }),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"odata-version": "3.0"
},
success: function (data) {
//console.log("done");
//console.log(data)
console.log("added: " + name);
},
error: function (response) {
console.log(response.responseText);
}
});
}
Thanks in advance.
Solution
I think the problem is with your data
property. Try using below code:
body: "{ '__metadata': { 'type': 'SP.Field' }, 'FieldTypeKind': 2, 'Title':'" + fieldName + "'}"
However you can also use JSOM to create multiple fields in a list.
Sources:
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange