Livesearch is a search technology, such that, as the user types the search keyword(s), an underground search is conducted, and suggestions are brought; suggestions related to the search keyword(s) typed by the user.
<form action="" method="post" name="search_form" id="search_form">
<div id="search">
<input name="searchWord" type="text" id="searchWord" onkeyup="showResult(this.value)" />
<input type="submit" name="Submit" value="Submit" />
<div id="livesearch"></div>
</div>
</form>
The HTML
codes above creates a form and sends whtever is typed to a javascript
function showResult
as it is being typed
The codes below are to be put in between <style>
and </style>
tags inside the head
tag. It may alternatively be used as an external script.
<style type="text/css">
#searchWord {
width:350px;
}
div#livesearch {
width:351px;
position:absolute;
left:-9999px;
z-index:20;
}
</style>
The CSS
codes above gives the textbox in which (a) search keyword(s) is typed and the div that will hold the result the same width, it also makes the div invisible.
The codes below are to be put in between <script>
and </script>
tags inside the head
tag. It may alternatively be used as an external script.
<script type="text/javascript">
function showResult(str) {
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
if (xmlhttp.responseText != "") {
document.getElementById("livesearch").style.position="relative";
document.getElementById("livesearch").style.left="0";
}
}
}
xmlhttp.open("GET","livesearch.php?str="+str,true);
xmlhttp.send();
}
</script>
<?php
$word = $_GET ['str']; // to get the search word
require_once ("connect.php"); // getting your connection script
$field_name = ""; // put in your field name inside the empty quotes
$table_name = ""; // put in your table name inside the empty quotes
$query = "SELECT $field_name FROM $table_name WHERE $field_name LIKE '%$word%'";
$result = mysql_query($query);
whille ($row = mysql_fetch_assoc($result)) {
echo "$row[$field_name] <br />";
}
?>
The php
code above should be put in a file called livesearch.php