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;
-
- $(document).ready(function ()
- {
-
- appWebUrl = decodeURIComponent(manageQueryStringParameter('SPAppWebUrl'));
- ExecuteOrDelayUntilScriptLoaded(getSearchResults, "sp.js");
-
- });
-
- 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()
- {
-
- var queryStr = "ContentTypeId:0x0100BEAD925C1BB0494FB50B0D4B0B9F7325*";
- ctx = new SP.ClientContext(appWebUrl);
- 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);
-
-
- }
-
-
- 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 results
var NewsTitle = this.Title != null ? this. Title: "";
document.getElementById(Title).innerText += NewsTitle;
});
- }
-
- function onQueryFail(sender, args)
- {
- alert('Query failed. Error:' + args.get_message());
- }
Note
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.