Get SharePoint search results using REST ajax call from Html


Hi,

We all aware the SharePoint exposed REST Api in order to perform various action at client side. There are some other ways also which a developer can adopt instead of REST(like CSOM) but that requires again client context. So it is recommenced that if we are using SharePoint Apps then use CSOM to get and update the data. Where as REST can be used in apps as well as some external applications.

This blog is intended to show how user can utilize the REST api and get the SharePoint Search results. There are few pre-requisites or conditions which must be fulfilled before proceeding further.

  • The machine where this code will be executed must have access to sharepoint site which means machine must be either in same domain or cross domain accessibility is there.
  • Search must be configured at SharePoint server.
  • Data must be properly crawled and you must get some results when searched for some keyword.

Steps:

1) Open the Explorer or any desired location and create a text file with ant desired name.

2) Now open this txt file in Notepad and click on “Save as..” option. Here select the “Save as type” as “All” and save the file in “.html” format as shown below:

1

3) Now open this file in any desired text editor(I love to use Notepad++ for same) and paste the following code:

<script src=”http://code.jquery.com/jquery-2.1.4.js&#8221; type=”text/javascript”></script>
<script type=”text/javascript”>
$(document).ready(function () {
$(“#SearchQuery”).click(function() {
$.ajax({
url: “http://<server URL>/_api/search/query?querytext='”+$(“#search-input”).val()+”‘&sourceid=%27b09a7990-05ea-4af9-81ef-edfab16c4e31%27″,
headers: { Accept: “application/json;odata=verbose” },
success: function (data) {

console.log(data.d);

},
error: function (jQxhr, errorCode, errorThrown) {
console.log(errorThrown);
}
});
});

});</script>
<input type=”text” id=”search-input”>
<input type=”button” id=”SearchQuery” value=”Search”>
<div id=”resultsDiv”></div>

Issues faced:

1) minFreeMemoryPercentageToActivateService memory issue:

2

Resolution: Open the web config of the web application and find out the entry with

<serviceHostingEnvironment aspNetCompatibilityEnabled=”true” />

to

<serviceHostingEnvironment aspNetCompatibilityEnabled=”true” minFreeMemoryPercentageToActivateService=”1″/>

Happy SharePointing 🙂