SharePoint Pals
 | Sign In
How to call a Search API using REST using JavaScript from SharePoint Hosted App in SharePoint 2013
by Sathish Nadarajan 15 Apr 2015
Author
SharePoint MVP
Visits   
Today  :   6     Total  :    13505

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.

blog comments powered by Disqus

SharePoint Pals

Pals
SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile

Training

Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community




SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to articles@sharepointpals.com in a word document.

Related Resources

Recent Tweets

Twitter January 15, 00:25
How To Enable Target Value And Actual Value In #D3 Gauge Chart https://t.co/VxSi4QnNrC

Twitter January 15, 00:24
How To Open #SharePoint List Hyperlink Column In Modal #Popup Window https://t.co/EQ7HkoZDkX

Twitter January 15, 00:24
Quick Introduction To #Asp.NetCore And It’s Features https://t.co/zAXObHCFpH

Twitter January 15, 00:22
How To Configure #PerformancePoint Services To Use Secure Store In #SharePoint 2013 https://t.co/LEwnUoI7EY

Twitter January 15, 00:21
How To Block Or Disable #Office365 Services https://t.co/Yvp2VPFIRP

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation