I have tried to make search suggestions like google...
i created a table tags and a single column tag and it has some tags stored in it but the problem is when i type nothing or something that is in the DB i get undefined as return
but when i type something that is not in DB i get sorry [which is correct]
i am using Ajax
my php code
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$searchvalue=$_GET['searchvalue'];
$con=mysqli_connect("localhost","root","","myweb") or die("error connecting db");
$sqlresult = mysqli_query($con,"SELECT tag FROM tags where tag like '".$searchvalue."%'");
$suggests="";
while($row = mysqli_fetch_array($sqlresult))
{
$suggests=$suggests.$row.',';
}
//$suggarray=explode(",",$suggests);
if(strlen($suggests)>0)
{
echo "found";
}
else
{
echo "sorry! for ".$searchvalue;
}
mysqli_close($con);
echo '</response>';
?>
JavaScript for ajax
// JavaScript for search ajax
var xmlHttp= createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
//alert("create obj");
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp =false;
}
}else{
try{
xmlHttp= new XMLHttpRequest();
}catch(e){
xmlHttp =false;
}
}
if(!xmlHttp)
alert("cant create that object hoss!");
else
return xmlHttp;
}
function searchprocess(){
//alert("start");
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
searchtext=encodeURIComponent(document.getElementById("searchvalue").value );
xmlHttp.open("GET", "pages/search_suggestions.php?searchvalue="+searchtext, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('searchprocess()', 1000);
}
}
function handleServerResponse(){
//alert("handle");
if(xmlHttp.readyState==4){
//alert("handle ready");
if(xmlHttp.status==200 || xmlHttp.status==304){
//alert("inside");
xmlResponse=xmlHttp.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message=xmlDocumentElement.firstChild.data;
document.getElementById("tempo").innerHTML=message;
setTimeout('searchprocess()', 1000);
}else{
alert("Something went wrong!");
}
}
}
// end of JavaScript for search ajax