Ajax – PHP Example : Suggestion Box using Ajax



We have already seen that the request made to the server is using the XMLHttpRequest object. In this tutorial we will be learning more details about the XMLHttpRequest object and its properties.

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{

var xmlhttp;
if (str.length==0) {
  document.getElementById("txtHint").innerHTML="";
  return;
}

if (window.XMLHttpRequest) {
  xmlhttp=new XMLHttpRequest();
} else {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    document.getElementById("txtHint").innerHTML 
	                             = xmlhttp.responseText;
  }
}
xmlhttp.open("GET","getCity.php?city="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<h3>Start Typing City Alphabet</h3>
<form action="">
City : 
<input type="text" id="city" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions : <span id="txtHint"></span></p> 

</body>
</html>

PHP Code :

Now Consider the following PHP file –

<?php
$cityList[]="Agra";
$cityList[]="Beed";
$cityList[]="Chennai";
$cityList[]="Delhi";
$cityList[]="Eluru";
$cityList[]="Firodkot";
$cityList[]="Ghana";
$cityList[]="Hajimpeth";
$cityList[]="Islampur";
$cityList[]="Jaipur";
$cityList[]="Kanpur";
$cityList[]="Laddakh";
$cityList[]="Mewar";
$cityList[]="Noida";
$cityList[]="Osmanabad";
$cityList[]="Pune";
$cityList[]="Qualalumpur";
$cityList[]="Raipur";
$cityList[]="Solapur";
$cityList[]="Takali";
$cityList[]="Uganda";
$cityList[]="Wai";

// get the parameter from URL
$city = $_REQUEST["city"]; 
$hint = "";

// Create Suggestion String 
if ($city !== "") {
   $city = strtolower($city ); 
   $len  = strlen($city );
   foreach($cityList as $cname) {
      if (stristr($city , substr($cname,0,$len))){ 
         if ($hint==="") { 
            $hint = $cname; 
         } else { 
            $hint .= ", $cname"; 
         }
      }
   }
}
echo $hint === "" ? "No Suggestion" : $hint;
?>

Output of Code :