In this article 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:
- var hostWebUrl;
- var appWebUrl;
-
- $(document).ready(function ()
- {
- hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
- appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));
-
- InsertItemToList();
- });
-
-
- 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];
- }
- }
- }
-
-
-
- function InsertItemToList()
- {
- var ctx = new SP.ClientContext(appWebUrl);
- var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
- var web = appCtxSite.get_web();
- var list = web.get_lists().getByTitle(listName);
- var listCreationInformation = new SP.ListItemCreationInformation();
- var listItem = list.addItem(listCreationInformation);
- listItem.set_item("Title", "Title1");
- listItem.update();
- ctx.load(listItem);
-
- 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.