How to: Query Search with the SharePoint 2013 JavaScript Client Object Model

Posted Thursday, April 18, 2013 10:08 PM by CoreyRoth

As a developer, if you have ever looked for information on how to query search in SharePoint, there is a good chance that you have ran into one of my articles.  I’ve been writing about how to query search in a variety of different ways since 2007.  They have always been some of the most popular articles on my site.  SharePoint 2013 has so many new ways to query search, it has taken me time to write up all of the different ways.  I am keeping the tradition alive by writing about how to query using the JavaScript Client Object Model provided by SP.Search.js.  You may have already seen my post on how to query from JavaScript and REST or my post on how to use the managed CSOM to Query Search.  You’ll find that querying from JavaScript looks very similar to the managed side of things.  In fact even the namespaces are the same and most of the code is quite similar between C# and JavaScript.  However, there are some nuances due to JavaScript so I wanted to share a complete code sample.

I am going to build my example inside a SharePoint-hosted app.  If you’re not familiar with that process yet, take a look at my Client Web Part post to get started.  When it comes to apps, you need to be sure and request permission to access search.  Do this by editing your AppManifest.xml and clicking on the permissions tab.  Select Search and then select QueryAsUserIgnoreAppPrincipal.  If you forget this step, you won’t get an error, your queries will simply just return zero results.

I’m going to put all of my code in the welcome page today.  My default.aspx page will have the same HTML as my other JavaScript post.  I simply add a textbox, a button, and a div to hold the results.  The user will type in his or her query, click the button, and then see search results.

<div>

    <label for="searchTextBox">Search: </label>

    <input id="searchTextBox" type="text" />

    <input id="searchButton" type="button" value="Search" />

</div>

 

<div id="resultsDiv">

</div>

We’re going to edit App.js next.  Since we’re in an App, I am assuming you already have code to get the SharePoint context since Visual Studio adds it for you.  If not, you can get it like this.

var context = SP.ClientContext.get_current();

I then add a click event handler to my document ready function.

$("#searchButton").click(function () {

});

In here, we’ll put our code to get a KeywordQuery and SearchExecutor object to execute our query in a similar manner to the Managed CSOM approach.  Now, we need to get our KeywordQuery object using the context object we already have.

var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(context);

Then, we set the query text using the value the user entered in the textbox with set_queryText().

keywordQuery.set_queryText($("#searchTextBox").val());

Now, we just need to create a SearchExecutor object and execute the query.  I am assigning the results of the query back to a global variable called results.  Since apps by default have ‘use strict’ enabled, you need to be sure and declare this first.

var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(context);

results = searchExecutor.executeQuery(keywordQuery);

Then like any CSOM code, we have to use executeQueryAsync to make the actual call to the server.  I pass it methods for success and failure.

context.executeQueryAsync(onQuerySuccess, onQueryError);

I generally prefer using REST to do my search queries.  However, when it comes to processing results, the data we get back from CSOM is typed better and much easier to access.  This results in less code that we have to deal with.  You can get quite a bit of data back such as the number of results returned just by exmaining results.m_value.  Each individual result can be found in results.m_value.ResultTables[0].ResultRows.  The managed properties of each row are typed directly on the object so that it means you can access them directly if you know the name (i.e.: Author, Write, etc). Iterating the values is simple using $.each.  Take a look at my example where I am writing the values into an HTML table.

function onQuerySuccess() {

    $("#resultsDiv").append('<table>');

 

    $.each(results.m_value.ResultTables[0].ResultRows, function () {

        $("#resultsDiv").append('<tr>');

        $("#resultsDiv").append('<td>' + this.Title + '</td>');

        $("#resultsDiv").append('<td>' + this.Path + '</td>');

        $("#resultsDiv").append('<td>' + this.Author + '</td>');

        $("#resultsDiv").append('<td>' + this.Write + '</td>');

        $("#resultsDiv").append('</tr>');

    });

 

    $("#resultsDiv").append('</table>');

}

The last thing to implement is the code to handle errors.  It just sends the error to an alert dialog.

function onQueryFail(sender, args) {

    alert('Query failed. Error:' + args.get_message());

}

When we run the app, it will look something like this.

SearchAppCSOMDefault

Executing a query will show us the four columns I specified in my $.each statement.

SearchAppCSOMResults

Pretty easy, right?  Here is the entire code snippet of my App.js.

'use strict';

 

var results;

 

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 () {

 

    $("#searchButton").click(function () {

        var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(context);

        keywordQuery.set_queryText($("#searchTextBox").val());

 

        var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(context);

        results = searchExecutor.executeQuery(keywordQuery);

 

        context.executeQueryAsync(onQuerySuccess, onQueryFail)

    });

});

 

 

function onQuerySuccess() {

    $("#resultsDiv").append('<table>');

 

    $.each(results.m_value.ResultTables[0].ResultRows, function () {

        $("#resultsDiv").append('<tr>');

        $("#resultsDiv").append('<td>' + this.Title + '</td>');

        $("#resultsDiv").append('<td>' + this.Author + '</td>');

        $("#resultsDiv").append('<td>' + this.Write + '</td>');

        $("#resultsDiv").append('<td>' + this.Path + '</td>');

        $("#resultsDiv").append('</tr>');

    });

 

    $("#resultsDiv").append('</table>');

}

 

function onQueryFail(sender, args) {

    alert('Query failed. Error:' + args.get_message());

}

Although, I typically prefer the REST interface for querying search.  I have to admit, I like the ease of working with the results in CSOM.  Hopefully, you find this sample useful.  Thanks!

I’ve also uploaded the full Visual Studio solution to MSDN Code Samples.

Comments

# How to: Query Search with the SharePoint 2013 J...

Friday, April 19, 2013 12:29 PM by How to: Query Search with the SharePoint 2013 J...

Pingback from  How to: Query Search with the SharePoint 2013 J...

# SharePoint Online: Usando el MO en Cliente de búsquedas desde una aplicación creada con NAPA!

Monday, May 6, 2013 4:38 PM by Blog del CIIN

En este artículo vamos a ver como podemos hacer uso del Modelo de Objetos en Cliente de búsquedas (sabor

# SharePoint Online: Usando el MO en Cliente de b&uacute;squedas desde una aplicaci&oacute;n creada con NAPA! | Pasi??n por la tecnolog??a...

Pingback from  SharePoint Online: Usando el MO en Cliente de b&uacute;squedas desde una aplicaci&oacute;n creada con NAPA! | Pasi??n por la tecnolog??a...

# 70-489 Developing Microsoft SharePoint Server 2013 Advanced Solutions &#8211; Preparation links | Martin Bodocky

Pingback from  70-489 Developing Microsoft SharePoint Server 2013 Advanced Solutions &#8211; Preparation links | Martin Bodocky

# re: How to: Query Search with the SharePoint 2013 JavaScript Client Object Model

Thursday, May 16, 2013 12:34 PM by Nico

Hi Corey, Great article!

Is there a way to set the returned properties by the query as the SelectProperties parameter with REST?

thx

# re: How to: Query Search with the SharePoint 2013 JavaScript Client Object Model

Thursday, May 16, 2013 12:37 PM by CoreyRoth

@Nico Yes, that's exactly what you do.  Specify the properties using the selectproperties parameter.  I usually test the URL I am going to use thoroughly in the browser before writing code with it.

# re: How to: Query Search with the SharePoint 2013 JavaScript Client Object Model

Monday, July 15, 2013 6:28 AM by ash

i get an unhandled exception at var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(context);

Error details

0x800a1391 - Microsoft JScript runtime error: 'Microsoft' is undefined

could you please help me out here

# re: How to: Query Search with the SharePoint 2013 JavaScript Client Object Model

Tuesday, July 16, 2013 10:38 AM by CoreyRoth

@Ash make sure you have all of the necessary script files loaded SP.JS, SP.Runtime.JS, SP.Search.JS.  Download my code sample from MSDN if you need a working example.

# re: How to: Query Search with the SharePoint 2013 JavaScript Client Object Model

Wednesday, April 9, 2014 5:19 AM by Hiren Kataria

Can you please guide me on how to enhance the code you have posted on MSDN so that we can also show Total number of search item returned?

# re: How to: Query Search with the SharePoint 2013 JavaScript Client Object Model

Friday, April 25, 2014 5:42 PM by Ubirajara

Hello! Great post!

I have a problem though: I found myself using the same query inside a content search webpart and through the code, but getting different results on each one. I'm listing all site collections on my server. I've got 5 on content search webpart, which is right, and 4 on my application page. I repeat: the same query.

Can you please comment? Thanks!!

# re: How to: Query Search with the SharePoint 2013 JavaScript Client Object Model

Wednesday, July 23, 2014 3:25 PM by Sabrina

Hi Corey, great post. Got a question for you. We're trying to use the Search API with CSOM in a CEWP. However we keep getting the 401- unauthorized. Using the App model you resolve that error by modifying the AppManifest.xml. How do we get around this purely client side? Does the Content Search WP have this setting built in automatically?

Thanks,

Sabrina

# re: How to: Query Search with the SharePoint 2013 JavaScript Client Object Model

Thursday, August 7, 2014 4:56 AM by srikanth

how to get the user profiles data in Sharepoint HostedApp through Search Service...

# re: How to: Query Search with the SharePoint 2013 JavaScript Client Object Model

Thursday, August 7, 2014 10:52 AM by CoreyRoth

@Sabrina If you are just using a CEWP in theory it should work as long as the site isn't anonymous.  It will use the credentials of the currently logged in user.  There is no way to set that app permission for a CEWP though.

# SharePoint 2013 JavaScript Client Object Model | Zimmer Answers

Pingback from  SharePoint 2013 JavaScript Client Object Model | Zimmer Answers

# How to create a search using sharepoint JSOM | DL-UAT

Monday, February 2, 2015 1:45 AM by How to create a search using sharepoint JSOM | DL-UAT

Pingback from  How to create a search using sharepoint JSOM | DL-UAT

# How to create a search using sharepoint JSOM | Question and Answer

Pingback from  How to create a search using sharepoint JSOM | Question and Answer

# ???????? &raquo; Search Results Web Part Change Query

Tuesday, June 2, 2015 12:36 PM by ???????? » Search Results Web Part Change Query

Pingback from  ????????  &raquo; Search Results Web Part Change Query

# SharePoint 2013 JavaScript Search files classes reference - Refinement Web Part classes in detail - Jos?? Quinto

Pingback from  SharePoint 2013 JavaScript Search files classes reference - Refinement Web Part classes in detail - Jos?? Quinto

# re: How to: Query Search with the SharePoint 2013 JavaScript Client Object Model

Friday, November 27, 2015 1:06 AM by Mayank

hi Corey.

thanks for sharing knowledge.

i tried this code :

is not working....m doing this on Page layout...can you suggest?

showing error:

"search request was unable to connect with search services"

i am working on dev server

# SharePoint Online: Usando el MO en Cliente de b&#250;squedas desde una aplicaci&#243;n creada con NAPA! &#8211; Blog del CIIN

Pingback from  SharePoint Online: Usando el MO en Cliente de b&#250;squedas desde una aplicaci&#243;n creada con NAPA! &#8211; Blog del CIIN

Leave a Comment

(required)
(required)
(optional)
(required)