Knowledgebase Home Page  >  SearchUnit
Search the Knowledge Base
How can I show a sample of the results as the user types, using AJAX / DHTML? (C#)
https://keyoti.com/kb/Default.aspx?ToDo=view&questId=210&catId=54

Options

Print this page
Email this to a friend

ASP.NET Search - AJAX

It is possible to use ASP.NET AJAX (or any kind of AJAX engine) to show the user a sample of results as they type into the search box.  This goes beyond our 'AutoComplete' feature, to actually show result titles, links and a summary.  It will impose more server load than normal functionality, as a search is performed for every key press, so it's advisable to use it on smaller indexes (<500 pages).

The following example will show any results (if there are any) in a floating DIV once the user has entered 3 chars.


1. Make a new ASPX page and paste in BELOW the <%@ Page directive at the top;


<%@ Register TagPrefix="searchengine" Namespace="Keyoti.SearchEngine.Web" Assembly="Keyoti2.SearchEngine.Web" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style>
    .resultsPanel
    {
     position: absolute; z-index:1000;
     left:50px;
     top: 50px;
     background-color: white;
     border:solid 2px #ddddff;
     font-family: @Batang;
     width: 600px;
     display:none;
     padding: 10px;
    }
   
    .resultSummary
    {
     border-bottom:solid 1px #ddddff;
     padding-bottom: 5px;
     padding-left: 5px;
     font-size:small;
    }
   
    </style>
    <script type="text/javascript">
   

     var queryText;


      function pageLoad() {
      }

      function query_keyUp(textBox) {

            queryText = textBox.value

            if(queryText.length>=3)
                runQuery(queryText);
            else
                document.getElementById('resultsPanel').style.display = 'none';
      }

      function runQuery(query) {       
          PageMethods.LoadResults(query, OnSucceeded, OnFailed);
      }

      function OnSucceeded(result, userContext, methodName) {

          if (methodName == "LoadResults") {
              var resultContent = "";       //the HTML we'll create with results
             
              //show/hide the panel depending on if we have results
              if (result.length > 0) document.getElementById('resultsPanel').style.display = 'block';
              else document.getElementById('resultsPanel').style.display = 'none';
             
              //generate html using result data
              for (var i = 0; i < result.length; i++) {
                  resultContent += "<a class='resultTitle' href='" + result[i].UriString + "'>" + result[i].Title + "</a>";
                  resultContent += "<p class='resultSummary'>";
                  resultContent += result[i].Summary;
                  resultContent += "</p>";
              }

             resultContent += "<p><a href='searchresults.aspx?QueryExpr=" + queryText + "&ResultsPage=1'>Show all results</a></p>"

              resultsPanel.innerHTML = resultContent;
          }
      }

      function OnFailed(error, userContext, methodName) {
          if (error !== null) {
              alert("An error occurred: " +           error.get_message());
          }
      }

 

        //THIS WILL DETECT A CLICK OUTSIDE OF THE SEARCH RESULTS AND HIDE IT
        document.onclick=check;
        function check(e){
            var target = (e && e.target) || (event && event.srcElement);
            var obj = document.getElementById('resultsPanel');
            var obj2 = document.getElementById('form1');
            checkParent(target)?obj.style.display='none':null;
            target==obj2?obj.style.display='block':null;
        }
        function checkParent(t){
            while(t.parentNode){
                if(t==document.getElementById('resultsPanel')){
                    return false
                }
                t=t.parentNode
            }
            return true
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
       
        <searchengine:searchbox id="SearchBox1" runat="server"
                ResultPageURL="SearchResults.aspx"
               
                >   
   </searchengine:searchbox>
    </div>
    <div style="color:Gray">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Why do we use it?It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

    </div>
    <div id='resultsPanel' class='resultsPanel'>
   
    </div>
    </form>
</body>
</html>


2. In the code-behind for the new ASPX page, change the Page_Load to

    protected void Page_Load(object sender, EventArgs e)
    {
        SearchBox1.QueryTextBox.Attributes.Add("onkeyup", "query_keyUp(this)");
    }

and add this method

[System.Web.Services.WebMethod]
    public static Keyoti.SearchEngine.Search.SearchResult LoadResults(string query)
    {
        string lic = "5550655C6258645D665768675F586436514D3A3C363B3C39433B4140414B404B47494B9";
        Keyoti.SearchEngine.Configuration configuration = new Keyoti.SearchEngine.Configuration();
        configuration.IndexDirectory = @"C:\Program Files\Keyoti Inc\Search for ASP.NET v3\Demos\VS2008\Keyoti_Search_ASP.NET_CSharp\IndexDirectory";

        Keyoti.SearchEngine.Search.SearchAgent sa = new Keyoti.SearchEngine.Search.SearchAgent(lic, configuration);
        return sa.Search(query, 1, 5);
    }


Note, that's a time trial license key for the LITE version, so it will need replacing with a more current one for your version.  Also, the 1 and 5 in the Search method, are the first result and last result number to get (ie. results 1 through 5).


3. Change the string

@"C:\Program Files\Keyoti Inc\Search for ASP.NET v3\Demos\VS2008\Keyoti_Search_ASP.NET_CSharp\IndexDirectory"

to point to the index directory you want to search.  It will need to be an absolute path.  If using an absolute path is not ideal, then it may be possible to pass the apps path to the LoadResults method, in the Javascript, and use that.


It won't show anything if either; there are no results or less than 3 chars are in the textbox.  This behaviour can be changed in the OnSucceeded function.  There is an OnFailed function which can be changed to display a message in the event things go wrong (server unreachable etc).

 


Related Questions:

Attachments:

No attachments were found.