This example shows how to do a search using the SharePoint 2013 REST API. In this sample we will create a page with a search box that displays results in a grid. To get started, create a new SharePoint-hosted app. Then, you must grant permissions to the App to use a search.

Develop the project using the following Method in the NAPA Tool

On your Developer Site, open the "Napa" Office 365 Development Tools and then choose Add New Project.



Permission

The following is an important procedure to be done before creating the app. Specify the permissions that your app needs as in the following. Choose the Properties button at the bottom of the page.


Default ASPX: Now, edit Default.aspx to add the HTML for our search box and button as well as a div tag to hold the results.
  1. <div>
  2. <label for="searchTextBox">Search: </label>
  3. <input id="searchTextBox" type="text" />
  4. <input id="searchButton" type="button" value="Search" />
  5. </div>
  6. <div id="resultsDiv">
  7. </div>
Source Code

Next, edit App.js to include your script to query the search and display the results. Add a click event handle to your document ready function. We'll put our code to do the query search here.
  1. var context = SP.ClientContext.get_current();
  2. // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
  3. $(document).ready(function () {
  4. var spAppWebUrl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
  5. $("#searchButton").click(function () {
  6. var queryUrl = spAppWebUrl + "/_api/search/query?querytext='" + $("#searchTextBox").val() + "'";
  7. $.ajax({ url: queryUrl, method: "GET", headers: { "Accept": "application/json; odata=verbose" }, success: onQuerySuccess, error: onQueryError });
  8. });
  9. });
  10. function onQuerySuccess(data) {
  11. var results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
  12. $("#resultsDiv").append('<table>');
  13. $.each(results, function () {
  14. $("#resultsDiv").append('<tr>');
  15. $.each(this.Cells.results, function () {
  16. $("#resultsDiv").append('<td>' + this.Value + '</td>');
  17. });
  18. $("#resultsDiv").append('</tr>');
  19. });
  20. $("#resultsDiv").append('</table>');
  21. }
  22. function onQueryError(error) {
  23. $("#resultsDiv").append(error.statusText)
  24. }
  25. //function to get a parameter value by a specific key
  26. function getQueryStringParameter(urlParameterKey) {
  27. var params = document.URL.split('?')[1].split('&');
  28. var strParams = '';
  29. for (var i = 0; i < params.length; i = i + 1) {
  30. var singleParam = params[i].split('=');
  31. if (singleParam[0] == urlParameterKey)
  32. return decodeURIComponent(singleParam[1]);
  33. }
  34. }
Publish






Output



Thanks for reading. Cheers!

Reference: msdn