Monday, August 18, 2014

Adding list items in sharepoint hosted app

On continuation of my last REST API series on how to use the REST API in SharePoint hosted App.

Download source code
Watch the screen cast in YouTube

In this post,We are going to see how to add the SharePoint list Item using simple html form.
For this I used to work on SharePoint hosted App.

I have one list named "Friends" in host web with three columns such as Title,First Name and Last Name.
So if you are not understand what is host web,app domain and cross domain call and about SP.Requestor.js file please read my previous posts where I explained these stuffs.

Simply we split into four manageable and understandable code block to perform this task.
1,Add variable to hold the web app URL and host web URL.

2,Utility function called "getQueryStringParameter" to parse the query string variable which contains the web app URL and host web URL.

3,On document ready, we need to load the SPRequestor.js file from the host web using "$.getScript" function.

4,Main function (addItem) to add the user inputs from UI to SharePoint List.

Step : 1

'use strict';
var hostweburl;
var appweburl;

Step : 2
function getQueryStringParameter(paramToRetrieve) {
    var params =
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];

Step :3
$(document).ready(function () {
      hostweburl =
     appweburl =
       var scriptbase = hostweburl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.RequestExecutor.js");

Step : 4

function addItem() {
      var executor = new SP.RequestExecutor(appweburl);
      var rest_data = JSON.stringify({
        '__metadata': { 'type': 'SP.Data.FriendsListItem' },
        'Title': $("#txtTitle").val(),
        'LastName': $("#txtLastName").val()
                    url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Friends')/items/?@target='" +   
           hostweburl + "'",
                     method: "POST",
                     body: rest_data,
                     headers: {"content-type": "application/json; odata=verbose" },
                     success: successHandler,
                     error: errorHandler