Tuesday, March 4, 2014

PHP Live Search

This is the example how to create live search where you get the search result while you type.
index.php
<html>
<head>
<script type="text/javascript">
function Search(src){
    var xmlhttp;
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest;
    }else{
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            document.getElementById("result").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","search.php?src="+src,true);
    xmlhttp.send();
}

</script>
</head
<body>
<input type="text" id="search" onkeyup="Search(this.value)" />
<div id="result"></div>
</body>
</html>

search.php
<?php
$src = (isset($_GET['srch'])) ?  $_GET['srch'] : "";
$query=mysql_query("SELECT field FROM table WHERE field LIKE '%".$src."%'");
while($result=mysql_fetch_assoc($query)){
          echo  $result['field'];
}
?>

No comments:

Post a Comment