Insert using REST API

In this article we can explore a simple code to Insert an Item using REST API.

Contacts List

Create a Contacts List for our purpose.

image

Script Inclusion

Following are the script files you need to include:

1. JQuery https://jquery.com/download/

2. JSON2 https://www.drupal.org/project/json2

You can copy the following script code with Microsoft & Yandex CDN links.

<script src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js”></script>

<script src=”http://yandex.st/json2/2011-10-19/json2.min.js”></script>

Insert Code

Following is the Insert Code to Insert an item.

<script type=”text/javascript”>

function test()

{

CreateListItemWithDetails(“Contacts”, _spPageContextInfo.webAbsoluteUrl, “New Contact”, success, failure);

}

function success()

{

alert(“success”);

}

function failure()

{

alert(“failed”);

}

function CreateListItemWithDetails(listName, webUrl, newItemTitle, success, failure) {

var itemType = “SP.Data.” + listName + “ListItem”;

var item = {

“__metadata”: { “type”: itemType },

“Title”: newItemTitle

};

$.ajax({

url: _spPageContextInfo.siteAbsoluteUrl + “/_api/web/lists/getbytitle(‘” + listName + “‘)/items”,

type: “POST”,

contentType: “application/json;odata=verbose”,

data: JSON.stringify(item),

headers: {

“Accept”: “application/json;odata=verbose”,

“X-RequestDigest”: $(“#__REQUESTDIGEST”).val()

},

success: function (data) {

success(data);

},

error: function (data) {

failure(data);

}

});

}

</script>

Invoke Code

Following would be the Invoke Code.

<input type=”button” value=”Click Me..” onclick=”javascript:test();”

Testing Code

You can use a new page & Content Editor web part to test the above code. On successful insert you should be getting the message below.

image

You can also verify the new item in the Contacts list.

image

This concludes Insertion using REST API code.

References

http://bit.ly/1R7kB11

Summary

In this post we have explored how to Insert an Item using REST API.

Leave a Reply

Your email address will not be published. Required fields are marked *