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.

Was it helpful?

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:

  1. Add a Field in the List in SharePoint 2013 Online Using REST API.

  2. Add Fields to SharePoint 2013 List Using JSOM.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top