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:

  1. var hostWebUrl;
  2. var appWebUrl;
  3. // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
  4. $(document).ready(function ()
  5. {
  6. hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
  7. appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));
  8. //Insert method
  9. InsertItemToList();
  10. });
  11. //This function is used to get the hostweb url
  12. function manageQueryStringParameter(paramToRetrieve)
  13. {
  14. var params =
  15. document.URL.split("?")[1].split("&");
  16. var strParams = "";
  17. for (var i = 0; i < params.length; i = i + 1)
  18. {
  19. var singleParam = params[i].split("=");
  20. if (singleParam[0] == paramToRetrieve)
  21. {
  22. return singleParam[1];
  23. }
  24. }
  25. }
  26. //Insert List Item to SP host web
  27. function InsertItemToList()
  28. {
  29. var ctx = new SP.ClientContext(appWebUrl);//Get the SharePoint Context object based upon the URL
  30. var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
  31. var web = appCtxSite.get_web(); //Get the Site
  32. var list = web.get_lists().getByTitle(listName); //Get the List based upon the Title
  33. var listCreationInformation = new SP.ListItemCreationInformation(); //Object for creating Item in the List
  34. var listItem = list.addItem(listCreationInformation);
  35. listItem.set_item("Title", "Title1");
  36. listItem.update(); //Update the List Item
  37. ctx.load(listItem);
  38. //Execute the batch Asynchronously
  39. ctx.executeQueryAsync(
  40. Function.createDelegate(this, success),
  41. Function.createDelegate(this, fail)
  42. );
  43. }
  44. function success()
  45. {
  46. alert("Item added successfully");
  47. }
  48. function fail(sender, args)
  49. {
  50. alert('Failed to get user name. Error:' + args.get_message());
  51. }
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.