Search in App web using REST API in SharePoint 2013

Implementation:

  1. Make use of Search REST service : <Site URL>/_api/search/query?querytext=”<SearchTerm>”.

  2. Process the returned JSON result.

  3. Add required Search Service Permission to App.Manifest. Add ‘Search’ in Scope and set permission to ‘QueryAsUserIgnoreAppPrincipal’.
Default.aspx
  1. <%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>  
  2.   
  3.     <%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>  
  4.   
  5.         <%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>  
  6.             <%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>  
  7.                 <%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>  
  8.   
  9.                     <%-- The markup and script in the following Content element will be placed in the <head> of the page --%>  
  10.                         <asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">  
  11.                             <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>  
  12.                             <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>  
  13.                             <script type="text/javascript" src="/_layouts/15/sp.js"></script>  
  14.                             <meta name="WebPartPageExpansion" content="full" />  
  15.   
  16.                             <!-- Add your CSS styles to the following file -->  
  17.                             <link rel="Stylesheet" type="text/css" href="../Content/App.css" />  
  18.   
  19.                             <!-- Add your JavaScript to the following file -->  
  20.                             <script type="text/javascript" src="../Scripts/App.js"></script>  
  21.                         </asp:Content>  
  22.   
  23.                         <%-- The markup in the following Content element will be placed in the TitleArea of the page --%>  
  24.                             <asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">  
  25.                                 Page Title  
  26.                             </asp:Content>  
  27.   
  28.                             <%-- The markup and script in the following Content element will be placed in the <body> of the page --%>  
  29.                                 <asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">  
  30.   
  31.                                     <div>  
  32.                                         <p id="message">  
  33.                                             <!-- The following content will be replaced with the user name when you run the app - see App.js -->  
  34.                                             initializing...  
  35.                                         </p>  
  36.                                     </div>  
  37.   
  38.                                     <!-- App Web Search-->  
  39.                                     <div id="searchDiv">  
  40.                                         <b>Search For</b>  
  41.                                         <input type="text" id="txtSearchTerm" />  
  42.                                         <input type="button" id="btnSearch" value="Search" onclick="searchAppWeb()" />  
  43.                                     </div>  
  44.                                     <div id="SearchResultsDiv"></div>  
  45.                                     <!--Search Ends-->  
  46.   
  47.                                 </asp:Content>  
App.js
  1. 'use strict';  
  2.   
  3. var context = SP.ClientContext.get_current();  
  4. var user = context.get_web().get_currentUser();  
  5.   
  6. // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model    
  7. $(document).ready(function() {  
  8.     getUserName();  
  9. });  
  10.   
  11. // This function prepares, loads, and then executes a SharePoint query to get the current users information    
  12. function getUserName() {  
  13.     context.load(user);  
  14.     context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);  
  15. }  
  16.   
  17. // This function is executed if the above call is successful    
  18. // It replaces the contents of the 'message' element with the user name    
  19. function onGetUserNameSuccess() {  
  20.     $('#message').text('Hello ' + user.get_title());  
  21. }  
  22.   
  23. // This function is executed if the above call fails    
  24. function onGetUserNameFail(sender, args) {  
  25.     alert('Failed to get user name. Error:' + args.get_message());  
  26. }  
  27.   
  28. //Search Implemenatation in App Web using Search REST API    
  29. //Do not forget to provide Search Permission in AppManifest file     
  30. var html;  
  31.   
  32. function searchAppWeb() {  
  33.   
  34.     //Get the Search Term from textbox    
  35.     var searchTerm = $("#txtSearchTerm").val();  
  36.   
  37.     //REST API query URL    
  38.     var queryUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + searchTerm + "'";;  
  39.   
  40.     //Empty the string    
  41.     html = "";  
  42.   
  43.     //Make the ajax call    
  44.     $.ajax({  
  45.         url: queryUrl,  
  46.         method: "GET",  
  47.         headers: {  
  48.             "Accept""application/json; odata=verbose"  
  49.         },  
  50.         success: onSearchSuccess,  
  51.         error: onSearchError  
  52.     });  
  53. }  
  54.   
  55. function onSearchSuccess(data) {  
  56.     // JSON object contains two elements which have search results    
  57.     //1. PrimaryQueryResult    
  58.     //2. SecondaryQueryResults (When documents are grouped on Host Web)    
  59.   
  60.     //Get PrimaryQueryResult and Render it in HTML Table format    
  61.     html = "<table>";  
  62.   
  63.     var primaryQueryResult = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;  
  64.   
  65.     if (primaryQueryResult != null && primaryQueryResult != undefined) {  
  66.         for (var iPrimaryResultCounter = 0; iPrimaryResultCounter < primaryQueryResult.length; iPrimaryResultCounter++) {  
  67.             html += "<tr><td>";  
  68.             html += primaryQueryResult[iPrimaryResultCounter].Cells.results[3].Value;  
  69.             html += "</td><td><a href=\""  
  70.             html += primaryQueryResult[iPrimaryResultCounter].Cells.results[6].Value;  
  71.             html += "\">" + primaryQueryResult[iPrimaryResultCounter].Cells.results[6].Value + "</a></td><tr>";  
  72.         }  
  73.     }  
  74.   
  75.     //Get SecondaryQueryResults and continue rendering it in HTML Table format    
  76.     var secondaryResult = data.d.query.SecondaryQueryResults;  
  77.     if (data.d.query.SecondaryQueryResults != null && data.d.query.SecondaryQueryResults != undefined) {  
  78.         for (var iSecondaryResultCounter = 0; iSecondaryResultCounter < data.d.query.SecondaryQueryResults.results.length; iSecondaryResultCounter++) {  
  79.             var resultBlock = data.d.query.SecondaryQueryResults.results[iSecondaryResultCounter].RelevantResults.Table.Rows.results;  
  80.             for (var iResults = 0; iResults < resultBlock.length; iResults++) {  
  81.                 html += "<tr><td>";  
  82.                 html += resultBlock[iResults].Cells.results[3].Value;  
  83.                 html += "</td><td><a href=\""  
  84.                 html += resultBlock[iResults].Cells.results[6].Value;  
  85.                 html += "\">" + resultBlock[iResults].Cells.results[6].Value + "</a></td><tr>";  
  86.             }  
  87.         }  
  88.     }  
  89.     html += "</table>";  
  90.     $("#SearchResultsDiv").append(html);  
  91.   
  92. }  
  93.   
  94. function onSearchError(err) {  
  95.     alert(JSON.stringify(err));  
  96. }