Slip 15 - B) Write a PHP script using AJAX concept, to give hint to user when he/she type city name in the text field.

 Solution:

HTML File:

<html>
<head>
<script>
function show(str)
{
if(str.length==0)
{
document.getElementById("txtHint").innerHTML = " ";
return;
}
else
{
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("txtHint").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","slip15-p2-q2.php?txt=" +str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
Enter City Name: <input type="text" name="txt" onkeyup="show(this.value)">
</form>
<p>Suggestions: <span id="txtHint"><span></p>
</body>
</html>

PHP File:

<?php
$a= array("Pune", "Mumbai", "Banglore", "Gujarat", "Kolkata", "Jaipur", "Surat", "Indore", "Lucknow", "Chandigarh", "Bhopal", "Patna" , "Kochi");
$game =  $_REQUEST["txt"];
$hint= " ";
if($game !== " ")
{
$len=strlen($game);
foreach($a as $name)
{
if (stristr($game, substr($name , 0 , $len)))
{
if($hint === " ")
{
$hint= $name;
}
else
{
$hint .= " , $name";
}
}
}
}
echo $hint === " " ? "no suggestion" : $hint;
?>

Post a Comment

0 Comments