Saturday, November 29, 2014



We saw how to fetch list items using REST services. We also saw various options and operators which can be applied on REST services while fetching list items. In this post we will see how to add new list item in list.

Adding list item through REST services is very simple, only things to remember are formats of field types, and the parameters to the service. Construct required input data and make REST service call and item gets created.

Following is the code snippet of creating new item in list.

function AddNewItem() 
 { 
var name = $("#txtName").val(); 
var class1 = $("#txtClass").val(); 
var age = $("#txtAge").val(); 
var city = $("#txtCity").val(); 
$.ajax({ 
        url: "/sites/OnePalSh/_api/web/lists/getbytitle('StudentsList')/items",         
        data: JSON.stringify({'__metadata': { 'type': 'SP.Data.StudentsListListItem' }, 'Title': 'Mr.', 'Name': name, 'Class' : class1, 'Age': age,'City': city }), 
        type: "POST",         
        headers: { 
            "ACCEPT": "application/json;odata=verbose", 
            "content-type": "application/json;odata=verbose", 
            "X-RequestDigest": $("#__REQUESTDIGEST").val() 
        }, 
        success: function (data) { 
            self.Students.push(new self.Student(data.d.ID,name,class1,age,city)); 
        }, 
        error: function (error) { 
            alert(JSON.stringify(error)); 
        } 
    }); 
 } 

If you see it closely the REST service URL remains same. There is change in method type, in this case it is POST. To add list item you need to give field values using the parameter: data. In Data you need to provide the metadata which is the type; this is important parameter with which REST service understands the schema of list. And others information in 'data' is nothing but the field values.  

You can get the type from REST service response. Enter the List Get Item's REST URL in browser and in response you will get this value like shown in below image. 


You need to use headers as mentioned above; we will see it in details in coming post.
Happy SharePoint Coding.

1 comment: