In this article I would like to share the code to get the search results in a SharePoint Hosted app using JavaScript.
SharePoint provides custom ways to get search results using REST. JSOM. Here I provide the code to get search results using the JavaScript object model.
getSearchResults Method
In this method I've got the search results based on content type and bind the search result title value in a lable on OnQuerySuccess.
Use the following code to get the search results.
- var ctx;
- 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 ()
- {
- // Get the URI decoded URLs.
- appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));
- ExecuteOrDelayUntilScriptLoaded(getSearchResults, "sp.js");
- });
- //This function is used to get the hostweb url
- function manageQueryStringParameter(paramToRetrieve)
- {
- var params = document.URL.split("?")[1].split("&");
- var strParams = "";
- for (var i = 0; i < params.length; i = i + 1)
- {
- var singleParam = params[i].split("=");
- if (singleParam[0] == paramToRetrieve)
- {
- return singleParam[1];
- }
- }
- }
- //Get Search results based on Content Type ID
- function getSearchResults()
- {
- // As per your requirement you can change the "queryStr", here I got the result based on content type
- var queryStr = "ContentTypeId:0x0100BEAD925C1BB0494FB50B0D4B0B9F7325*"; //content Type ID
- ctx = new SP.ClientContext(appWebUrl); // get current App Context
- var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(ctx);
- keywordQuery.set_queryText(queryStr);
- var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(ctx);
- results = searchExecutor.executeQuery(keywordQuery);
- ctx.executeQueryAsync(onQuerySuccess, onQueryFail);
- // method will exit here and onQuerySuccess or onQueryFail will be called asynchronously
- }
- //bind the Results in Div
- function onQuerySuccess()
- {
- var searchResult= results.m_value.ResultTables[0].ResultRows;
- $.each(searchResults, function () {//if you want more properties you can get by managed properties in search resultsvar NewsTitle = this.Title != null ? this. Title: "";document.getElementById(Title).innerText += NewsTitle;});
- }
- function onQueryFail(sender, args)
- {
- alert('Query failed. Error:' + args.get_message());
- }
In the AppManifest.xml file provide QueryAsUserIgnoreAPPPrincipal permission to the Search.

Summary
In this article we explored how to get the search results based on Content Type ID using JavaScript. I hope that the code above will be really useful for a SharePoint hosted app.

Join the conversation! Your thoughts help the community grow.