I was trying to make a search bar using AJAX which searches for a user in the database. The AJAX is working fine; it displays correct message when nothing is typed or no user found. The problem is, even if the user is found it displays no user found. This is the PHP file:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
require_once("includes/connection.php");
echo '<response>';
$user=$_GET['user'];
if($user==""){
echo "type the username";
}
else{
$query="SELECT email_id FROM users WHERE email_id={$user}";
$user_result = mysql_query($query,$connection);
if($user_result){
echo "yeah {$user} exists";
}
else{
echo "no such user as {$user} exists";
}
}
echo '</response>';
?>
I'm not including the function creating the xmlHTTP object but this is the rest of the JavaScript code:
function start()
{
if(xmlHttp){
try{
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
user= encodeURIComponent(document.getElementById("user_input").value);
xmlHttp.open("GET","search.php?user="+user,true);
xmlHttp.onreadystatechange = mainFunctionHandler;
xmlHttp.send(null);
}else{
setTimeout('start()',1000);
}
}catch(e){
alert(e.toString());
}
}
}
function mainFunctionHandler()
{
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("divD").innerHTML=message;
setTimeout('start()',1000);
}else{
alert("something went wrong");
}
}
}