Auto Complete/Suggestion in SharePoint 2010 Search Text box with jQuery – Part 2

As I told, here is the second part of the Auto Complete/Suggestion functionality in SharePoint 2010 Search Text box using jQuery. The first post can be found here.

In this blog post I will explain how to attach the auto complete/suggestion functionality to the search text box in the results page of the Search site. Also, we will see how to add the search query into the Search Keywords list so that the suggestion terms need not be added manually by the users. The code implemented here would be used in the search results page.

UPDATE: I have published this application here in CodePlex as well blogged about it briefly over here about the functionality as well as the deployment steps. Check it out if you do not want to get in to the coding side.

I’m going to explain only the modifications that I have done to the code in the previous post.

1. Modify the onQuerySucceeded function as shown below. I have described the code in comments


function onQuerySucceeded(sender, args) {
   listItemEnumerator = collListItem.getEnumerator();
   // declare a bool variable which we will use later
   termPresent = false;
   // get the query string value of key 'k' which has the search query and store in a variable
   // after decoding it
   srchTerm = decodeURI(JSRequest.QueryString["k"]);
   while (listItemEnumerator.moveNext()) {
       oListItem = listItemEnumerator.get_current();

   // check if the value in the Title columns in equal to search query
   // by converting them in to lowercase
   if( oListItem.get_item('Title').toLowerCase() == srchTerm.toLowerCase())
   {
      // if they are equal then change the value of the bool variable to true
      // which means the search query need not be added to the Search Keywords list
      termPresent = true;
   }
   listItemInfo += ',' + oListItem.get_item('Title');
 }

   $(".ms-sbplain").autocomplete({
   source: listItemInfo.split(",")
   });

   // check the value of the bool variable, if it is false then call the createListItem function
   // which will add the list item to the Search Keywords list
  if(termPresent == false)
  {
    createListItem(srchTerm);
  }
 }

2. Create the createListItem function with the below code.

function createListItem(srchTerm)
 {
   // create a new list item to be added in the Search Keywords list
   itemCreateInfo = new SP.ListItemCreationInformation();
   // add the item to the oList which is the Search Keywords list
   this.oListItem = oList.addItem(itemCreateInfo);
   // set the value of the title column of the list item to the search query
   oListItem.set_item('Title', srchTerm);
   // update the the list item
   oListItem.update();
   // load the list item
   clientContext.load(oListItem);
   // declare the delegates to be executed on success and on failure
   clientContext.executeQueryAsync(Function.createDelegate(this, this.onCreateSucceeded), Function.createDelegate(this, this.onQueryFailed));
 }

3. Create an empty onCreateSucceeded function.

function onCreateSucceeded() {
 // just an empty function
 }

Here is the complete code without comments.

<script type="text/javascript" src="/_layouts/SPAutoSuggestion/jquery-1.7.js"></script>
<script type="text/javascript" src="/_layouts/SPAutoSuggestion/jquery.ui.core.js"></script>
<script type="text/javascript" src="/_layouts/SPAutoSuggestion/jquery.ui.widget.js"></script>
<script type="text/javascript" src="/_layouts/SPAutoSuggestion/jquery.ui.position.js"></script>
<script type="text/javascript" src="/_layouts/SPAutoSuggestion/jquery.ui.autocomplete.js"></script>
<link href="/_layouts/SPAutoSuggestion/jquery-ui.CSS" rel="stylesheet" type="text/css" />

<script type="text/javascript">
JSRequest.EnsureSetup();
var clientContext;
var oList;
var camlQuery;
var listItemInfo = '';
var listItemEnumerator;
var termPresent;
var srchTerm;
var oListItem;
var itemCreateInfo;

$(document).ready(function () {
ExecuteOrDelayUntilScriptLoaded(Post_COM_Load, "sp.js");
});

function Post_COM_Load() {
clientContext = new SP.ClientContext.get_current();
oList = clientContext.get_web().get_lists().getByTitle('Search Keywords');

camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View/>');
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem, 'Include(Title)');
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {

listItemEnumerator = collListItem.getEnumerator();

termPresent = false;

srchTerm = decodeURI(JSRequest.QueryString["k"]);
while (listItemEnumerator.moveNext()) {
oListItem = listItemEnumerator.get_current();
if( oListItem.get_item('Title').toLowerCase() == srchTerm.toLowerCase())
{
termPresent = true;
}
listItemInfo +=
',' + oListItem.get_item('Title');
}

$(".ms-sbplain").autocomplete({
source: listItemInfo.split(",")
});

if(termPresent == false)
{
createListItem(srchTerm);
}
}

function createListItem(srchTerm)
{
itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Title', srchTerm);
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onCreateSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onCreateSucceeded() {
}

function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

4. The above code has to be added to a Content Editor Web Part in the results page of your Search site.

5. After you do a search with a query text, for example “Microsoft SharePoint” in your search site.

you can see that the query text has been added in the Search Keywords list as shown below

which would also eventually appear in the suggestions list as you type in your search text boxes as shown below.

Advertisements