Jump to content

Incremental Search


pingo

Recommended Posts

Hello AllI would like to implement a incremental search feature for my web site. What is Incremental Search ? When you start typing the name of your document, the page has to narrow down(&display) the words which has either the words you typed in or should begin with those words.... Say i start typing "W3" ... if my page has W3forum, W3School, W3Members, ManageW3forum... etc, It should display all these words which has W3 in it.I am trying to find how i can implement this feature. Please kindly chip in your ideas.RegardsVignesh

Link to comment
Share on other sites

The best way to use this is to make use of AJAX, a scripting technique that combines an xml document (to house the data), an sql database (to hold the variables) and a JavaScript to run between the two.For your project you might not even need an XML page - you may be able to just place it right inside your document. (I'll assume you're using a server with PHP and some form of SQL enabled)To generate a completely functional live search form you will need:-a simple HTML form -a JavaScript -a PHP page -an XML document For simplicities sake, I'll use the example W3Schools provides.1. You start with your basic HTML form box. Your code may look something like this:

<html><head><script src="livesearch.js"></script> <style type="text/css"> #livesearch  {   margin:0px;  width:194px;   }#txt1  {   margin:0px;  } </style></head><body><form><input type="text" id="txt1" size="30"onkeyup="showResult(this.value)"><div id="livesearch"></div></form></body></html> 

Within the head tag you specify the location of the javascript document that will run in between the Form, the database, and the XML document.2. The JavaScriptThe function of the JavaScript is to allow the search box to retrieve the desired results without refreshing the page. This allows for increased usability and makes your site much more user friendly. The JavaScript is the "middle man" between the static HTML and the dynamic PHP document. The JavaScript will tell the browser where to look for the PHP file. It should look something like this (customize for your sites compatability):

var xmlHttpfunction showResult(str){if (str.length==0) {  document.getElementById("livesearch"). innerHTML=""; document.getElementById("livesearch"). style.border="0px"; return }xmlHttp=GetXmlHttpObject()if (xmlHttp==null) { alert ("Browser does not support HTTP Request") return } var url="livesearch.php"url=url+"?q="+strurl=url+"&sid="+Math.random()xmlHttp.onreadystatechange=stateChanged xmlHttp.open("GET",url,true)xmlHttp.send(null)} function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {  document.getElementById("livesearch"). innerHTML=xmlHttp.responseText; document.getElementById("livesearch"). style.border="1px solid #A5ACB2"; } }function GetXmlHttpObject(){var xmlHttp=null;try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); }catch (e) { // Internet Explorer try  {  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");  } catch (e)  {  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");  } }return xmlHttp;}

The var url="livesearch.php" statement tells the browser that the variables to execute the AJAX live search are in the file livesearch.php3. The PHP DocumentWhile the HTML form focused on the visual display of the page, and the JavaScript focused on how to communicate the code, the PHP document determines how it will be displayed. For example, when you start typing the list of links will begin to pop up under the box. Whether or not they open in a new window, what color they are, whethere there is CSS involved etc is all specified by this document.The Code:

<?php$xmlDoc = new DOMDocument();$xmlDoc->load("links.xml");$x=$xmlDoc->getElementsByTagName('link');//get the q parameter from URL$q=$_GET["q"];//lookup all links from the xml file if length of q>0if (strlen($q) > 0){$hint="";for($i=0; $i<($x->length); $i++) { $y=$x->item($i)->getElementsByTagName('title'); $z=$x->item($i)->getElementsByTagName('url'); if ($y->item(0)->nodeType==1)  {  //find a link matching the search text  if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))   {   if ($hint=="")    {    $hint="<a href='" .     $z->item(0)->childNodes->item(0)->nodeValue .     "' target='_blank'>" .     $y->item(0)->childNodes->item(0)->nodeValue . "</a>";    }   else    {    $hint=$hint . "<br /><a href='" .     $z->item(0)->childNodes->item(0)->nodeValue .     "' target='_blank'>" .     $y->item(0)->childNodes->item(0)->nodeValue . "</a>";    }   }  } }}// Set output to "no suggestion" if no hint were found// or to the correct valuesif ($hint == "") { $response="no suggestion"; }else { $response=$hint; }//output the responseecho $response;?>

the $xmlDoc->load("links.xml") statement tells the server that the data it will be extracting (the actual search results) are in the file links.xmlFinally, the part you've been waiting for:4. The XML documentThe XML document is simply a list of the results (pure data). As in all XML documents, you define the tags. If you change a tag from the example you must also change how it is displayed in the PHP document.Here is the sample list of search results: (The document can be expanded to include thousands of possible results)

<?xml version="1.0" encoding="ISO-8859-1" ?> <pages><link><title>HTML DOM alt Property</title> <url>http://www.w3schools.com/htmldom/prop_img_alt.asp</url> </link><link><title>HTML DOM height Property</title> <url>http://www.w3schools.com/htmldom/prop_img_height.asp</url> </link><link><title>HTML a tag</title> <url>http://www.w3schools.com/tags/tag_a.asp</url> </link><link><title>HTML br tag</title> <url>http://www.w3schools.com/tags/tag_br.asp</url> </link><link><title>CSS background Property</title> <url>http://www.w3schools.com/css/pr_background.asp</url> </link><link><title>CSS border Property</title> <url>http://www.w3schools.com/css/pr_border.asp</url> </link><link><title>JavaScript Date() Method</title> <url>http://www.w3schools.com/jsref/jsref_date.asp</url> </link><link><title>JavaScript anchor() Method</title> <url>http://www.w3schools.com/jsref/jsref_anchor.asp</url> </link></pages>

Using XML to hold the data is the easiest way to do so, because you can come back to the search box (even months after you created it) to add more results and you won't get confused by code you don't remember writing. You just keep expanding until you're done.5. Putting it all togetherOnce all three parts have been uploaded to a server which supports PHP (Make sure your file extension is .php for the html page and the php script page, or that you've specified all pages to be parsed for PHP in your .htaccess) and all links are correct you should test your search box for accuracy. If you find its not working, make sure the paths to the files are correct and that they are saved under the right directories. If you're still having problems double check your server capabilities because this script does work if properly configured.If you need any more help pm me.Good Luck!

Link to comment
Share on other sites

Thank youI am using .ASP instead of .PHP, and using an SQL database with a query instead of a XML doc.I am able to get the needed data, but it doesnt do the 4 items listed.I tried using some of your info, but it errors out all the time when using this document.getElementById("txtHint"). style.border="0px";or some other bit of info.?????

Link to comment
Share on other sites

I ran the scripts as noted on my server and I believe I found the error.I think that when i copied the code into the codebox one of the lines in the html form document didn't copy correctly, which would explain why it returns a blank form feild.The code: "<script src="livesearch.js"></script> " should read "<script src="livesearch.js"></script>"I guess the "<" character didn't copy over as desired.I have corrected the error in the first post I made but just to be sure, this is the correct HTML document:<html><head><script src="livesearch.js"></script> <style type="text/css"> #livesearch { margin:0px; width:194px; }#txt1 { margin:0px; } </style></head><body><form><input type="text" id="txt1" size="30"onkeyup="showResult(this.value)"><div id="livesearch"></div></form></body></html>

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...