Getting List items In SharePoint Hosted App

In this blog, you will learn about SharePoint Hosted apps getting list items.

Step 1: Create a list .

list
Step 2: Open Visual Studio and add SharePoint Add-in (Sharepoint app name changed to Add-in) .

Sharepoint Add-in

Step 3: Edit App.js file with the code given below and add Div tag in ContentPlaceHolderID to display the query result.

code

  1. var Items = null;  
  2. 'use strict';  
  3. var listItems;  
  4. var hostweburl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));  
  5. var appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));  
  6. $(document).ready(function() {  
  7.     SP.SOD.executeFunc('sp.js''SP.ClientContext', ListItems)  
  8. });  
  9.   
  10. function ListItems() {  
  11.     var context = new SP.ClientContext(appweburl);  
  12.     var ContextSite = new SP.AppContextSite(context, hostweburl);  
  13.     var web = ContextSite.get_web();  
  14.     context.load(web);  
  15.     var list = web.get_lists().getByTitle('TestList');  
  16.     var caml = new SP.CamlQuery();  
  17.     caml.set_viewXml("<View><Query><Where><BeginsWith><FieldRef Name='Title' /><Value Type='Text'>N</Value></BeginsWith></Where></Query></View>"); // U can change the query for getting desired result   
  18.     Items = list.getItems(caml);  
  19.     context.load(Items);  
  20.     context.executeQueryAsync(onSucceededCallback, onFailedCallback);  
  21. }  
  22.   
  23. function onSucceededCallback(sender, args) {  
  24.     var enumerator = Items.getEnumerator();  
  25.     var myText = 'Items in TestList that start with "N": <br><br>';  
  26.     while (enumerator.moveNext()) {  
  27.         var listItem = enumerator.get_current();  
  28.         myText += 'Title: ' + listItem.get_item('Title') + '<br>';  
  29.         myText += 'ID: ' + listItem.get_id() + '<br><br>';  
  30.     }  
  31.     myDiv.innerHTML = myText;  
  32. }  
  33.   
  34. function onFailedCallback(sender, args) {  
  35.     var myText = '<p>The request failed: <br>';  
  36.     myText += 'Message: ' + args.get_message() + '<br>';  
  37.     myDiv.innerHTML = myText;  
  38. }  
  39.   
  40. function getQueryStringParameter(paramToRetrieve) {  
  41.     var params = document.URL.split("?")[1].split("&");  
  42.     for (var i = 0; i < params.length; i = i + 1) {  
  43.         var singleParam = params[i].split("=");  
  44.         if (singleParam[0] == paramToRetrieve) return singleParam[1];  
  45.     }  
  46. }  
Step 4: Before deploying the code, change the permission, given below:

code

Step 5: Deploy the code and Trust the app.
Trust
Step 6: See the result, given below:

result