46. Click on SharePoint 2013 Products ...  from all apps

SharePoint 2013 Hosting :: How To Insert Items Into a SharePoint Host Web List Using SharePoint Hosted APP

This article explains how to insert items into a SharePoint Host web list using SharePoint hosted APP.  I would like to share the code to insert items into a host web list using JavaScript.
Use the following JavaScript code to insert an Item:

ahp_freehostSHP(1)

var hostWebUrl;
var appWebUrl;
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function ()
{
hostWebUrl = decodeURIComponent(manageQueryStringParameter(‘SPHostUrl’));
appWebUrl = decodeURIComponent(manageQueryStringParameter(‘SPAppWebUrl’));
//Insert method
InsertItemToList();
});
//This function is used to get the hostweb url
function manageQueryStringParameter(paramToRetrieve)
{
var params =
document.URL.split(“?”)[1].split(“&”);
var strParams = “”;
for (var i = 0; i < params.length; i = i + 1)
{
var singleParam = params[i].split(“=”);
if (singleParam[0] == paramToRetrieve)
{
return singleParam[1];
}
}
}
//Insert List Item to SP host web
function InsertItemToList()
{
var ctx = new SP.ClientContext(appWebUrl);//Get the SharePoint Context object based upon the URL
var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
var web = appCtxSite.get_web(); //Get the Site
var list = web.get_lists().getByTitle(listName); //Get the List based upon the Title
var listCreationInformation = new SP.ListItemCreationInformation(); //Object for creating Item in the List
var listItem = list.addItem(listCreationInformation);
listItem.set_item(“Title”, “Title1″);
listItem.update(); //Update the List Item
ctx.load(listItem);
//Execute the batch Asynchronously
ctx.executeQueryAsync(
Function.createDelegate(this, success),
Function.createDelegate(this, fail)
);
}
function success()
{
alert(“Item added successfully”);
}
function fail(sender, args)
{
alert(‘Failed to get user name. Error:’ + args.get_message());
}

Note
In the AppManifest.xml file provide write permission to the SiteCollection.

Summary

This article explored how to insert list items into a host web list from a SharePoint Hosted app using JavaScript.