in

Dot Net Mafia

Group site for developer blogs dealing with (usually) .NET, SharePoint 2013, SharePoint 2010, Office 365, SharePoint Online, and other Microsoft products, as well as some discussion of general programming related concepts.

This Blog

Syndication

Archives

Corey Roth [MVP]

A SharePoint MVP bringing you the latest time saving tips for SharePoint 2013, Office 365 / SharePoint Online and Visual Studio 2013.

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

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... said:

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

April 19, 2013 12:29 PM
 

Blog del CIIN said:

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

May 6, 2013 4:38 PM
 

SharePoint Online: Usando el MO en Cliente de búsquedas desde una aplicación creada con NAPA! | Pasi??n por la tecnolog??a... said:

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...

May 6, 2013 4:46 PM
 

70-489 Developing Microsoft SharePoint Server 2013 Advanced Solutions – Preparation links | Martin Bodocky said:

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

May 9, 2013 10:01 AM
 

Nico said:

Hi Corey, Great article!

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

thx

May 16, 2013 12:34 PM
 

CoreyRoth said:

@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.

May 16, 2013 12:37 PM
 

ash said:

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

July 15, 2013 6:28 AM
 

CoreyRoth said:

@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.

July 16, 2013 10:38 AM
 

Hiren Kataria said:

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?

April 9, 2014 5:19 AM
 

Ubirajara said:

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!!

April 25, 2014 5:42 PM
 

Sabrina said:

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

July 23, 2014 3:25 PM
 

srikanth said:

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

August 7, 2014 4:56 AM
 

CoreyRoth said:

@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.

August 7, 2014 10:52 AM
 

SharePoint 2013 JavaScript Client Object Model | Zimmer Answers said:

Pingback from  SharePoint 2013 JavaScript Client Object Model | Zimmer Answers

December 6, 2014 10:44 PM
 

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

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

February 2, 2015 1:45 AM
 

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

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

February 8, 2015 9:50 PM
 

???????? » Search Results Web Part Change Query said:

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

June 2, 2015 12:36 PM
 

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

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

July 1, 2015 3:50 AM
 

Mayank said:

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

November 27, 2015 1:06 AM
 

SharePoint Online: Usando el MO en Cliente de búsquedas desde una aplicación creada con NAPA! – Blog del CIIN said:

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

February 8, 2016 7:15 AM

Leave a Comment

(required)  
(optional)
(required)  
Add

About CoreyRoth

Corey Roth is an independent SharePoint consultant specializing in ECM, Apps, and Search.
2015 dotnetmafia.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems