How to call a Search API using REST using JavaScript from SharePoint Hosted App in SharePoint 2013

Sathish Nadarajan
 
Solution Architect
April 15, 2015
 
Rate this article
 
Views
22407

In this article, let us see, how to create a simple SharePoint Hosted Application and make a REST API call using the JavaScript in SharePoint 2013.

Let us go with a step by step procedures.

1. Open the Visual Studio with “Run as Administrator”

image

2. On the New Project, Select “App for SharePoint 2013”

3. Give a Site Collection on which we want to deploy our App. I would suggest, for the development purpose, Give any of the “Developer Site” template.

image

4. Select the “SharePoint Hosted” on the dropdown and select “Finish”.

5. The solution will looks like as below.

image

6. Our App is going to get launched with this Default.aspx. If you closely look at that page, there is a reference for a file called “App.Js”. Actually this is the file which we are going to do most of our Activities.

7. As all of us know, that the SharePoint Hosted App cannot use any Server Side Coding. Hence, all the coding needs to be done by using JavaScript CSOM only.

8. That’s the reason, this App.Js is getting more importance.

9. Let us open App.Js and you can find the document.ready Event readily available for us.

10. There are certain functionalities by default written to show a sample for us.

11. We are not going to use them.

12. The App.Js looks like

 'use strict';
 
 var context = SP.ClientContext.get_current();
 var user = context.get_web().get_currentUser();
 
 // 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 () {
     getUserName();
 });
 
 // This function prepares, loads, and then executes a SharePoint query to get the current users information
 function getUserName() {
     context.load(user);
     context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
 }
 
 // This function is executed if the above call is successful
 // It replaces the contents of the 'message' element with the user name
 function onGetUserNameSuccess() {
     $('#message').text('Hello ' + user.get_title());
 }
 
 // This function is executed if the above call fails
 function onGetUserNameFail(sender, args) {
     alert('Failed to get user name. Error:' + args.get_message());
 }
 

13. Now let me modify this App.Js as below. The Javascripts are self-explanatory.

 'use strict';
 
 var context = SP.ClientContext.get_current();
 var user = context.get_web().get_currentUser();
 var Results;
 
 // 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 () {
     //getUserName();
     showToolbar();
 });
 
 function showToolbar()
 {
     $("toolbarDiv").show();
 }
 
 function executeQuery(queryTerms)
 {
     Results = {
         element: '',
         url: '',
         init: function (element) {
             Results.element = element;
             Results.url = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + queryTerms + "'";
         },
         load: function () {
             $.ajax({
                 url:Results.url,
                 method: "GET",
                 headers: { "ACCEPT": "application/json;odata=verbose" },
                 success: Results.onSuccess,
                 error : Results.onError
             });
         },
         onError: function (error) {
             alert(JSON.stringify(error));
         },
         onSuccess: function (data) {
 
             var results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
 
             $("#resultsDiv").append('<table>');
 
             $.each(results, function () {
                 $("#resultsDiv").append('<tr>');
                 $.each(this.Cells.results, function () {
                     $("#resultsDiv").append('<td>' + this.Value + '</td>');
                 });
                 $("#resultsDiv").append('</tr>');
             });
 
             $("#resultsDiv").append('</table>');
 
 
             
         }
     }
 
     Results.init($("resultsDiv"));
     Results.load();
 }
 
 // This function prepares, loads, and then executes a SharePoint query to get the current users information
 function getUserName() {
     context.load(user);
     context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
 }
 
 // This function is executed if the above call is successful
 // It replaces the contents of the 'message' element with the user name
 function onGetUserNameSuccess() {
     $('#message').text('Hello ' + user.get_title());
 }
 
 // This function is executed if the above call fails
 function onGetUserNameFail(sender, args) {
     alert('Failed to get user name. Error:' + args.get_message());
 }
 

14. And the Default.aspx will be like

 <%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>
 
 <%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>
 
 <%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
 <%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
 <%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
 
 <%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
 <asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
     <script type="text/javascript" src="../Scripts/jquery-1.7.1.min.js"></script>
     <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
     <script type="text/javascript" src="/_layouts/15/sp.js"></script>
 
     <!-- Add your CSS styles to the following file -->
     <link rel="Stylesheet" type="text/css" href="../Content/App.css" />
 
     <!-- Add your JavaScript to the following file -->
     <script type="text/javascript" src="../Scripts/App.js"></script>
 </asp:Content>
 
 <%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
 <asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
     Page Title
 </asp:Content>
 
 <%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
 <asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
 
     <div>
         <p id="message">
             <!-- The following content will be replaced with the user name when you run the app - see App.js -->
             initializing...
         </p>
     </div>
 
     <div id="toolbarDiv" >
         <input type="text" style="width:200px" id="queryTerms" />
         <button onclick="executeQuery($get('queryTerms').value);return false;">Search</button>
     </div>
     <div id="resultsDiv">
 
     </div>
 </asp:Content>
 

15. With this we are ready to deployment. But before the deployment, make sure that our APP has appropriate permission to do a search. For that, on the AppManifest.xml file, the following permission level should be given.

image

DOWNLOAD THE SOURCE HERE

Happy Coding.

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment