Ajax Suggest

Ajax Suggest


Posted in : Ajax Posted on : March 7, 2011 at 5:48 PM Comments : [ 0 ]

This section contains the detail about how the input(start letter) typed by you is used by Ajax to advise you the possible name or names.

Ajax Suggest

This section contains the detail about how the input(start letter) typed by you is used by Ajax to advise you the possible name or names.

When you type the first letter in the input box, it sends this letter to server(here PHP server) using Ajax's open and send method of xmlhttp object. The server match the possible word/words from array and sends back as Ajax response. Then the using onreadystatechange event, it shows the suggestions or hints to you.

Example

The HTML and Ajax code at client side is given below :

<html>
<head>
<script type="text/javascript">
function suggest(strg)
{
if (strg.length==0)
{
document.getElementById("hints").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("hints").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.php?s="+strg,true);
xmlhttp.send();
}
</script>
</head
<body>

<p><b>Type your maiden name :: Suggestion will appear below input box :</b></p>
<form>
Your Maiden Name: <input type="text" onkeyup="suggest(this.value)" size="20" />
</form>
<p>Hint/Advice: <span id="hints"></span></p>

</body>
</html>

The PHP code at server side to handle Ajax request is provided below :

<?php
// Array named as x[] for storing suggestions
$x[]="Ankit";
$x[]="Bharat";
$x[]="Chanchal";
$x[]="Divya";
$x[]="Ekta";
$x[]="Faiz";
$x[]="Gyan";
$x[]="Himesh";
$x[]="Inndu";
$x[]="John";
$x[]="Kavita";
$x[]="Lokesh";
$x[]="Neha";
$x[]="OmPrakash";
$x[]="Pawan";
$x[]="Anand";
$x[]="Rohit";
$x[]="Chandni";
$x[]="Deepak";
$x[]="Eshu";
$x[]="Eshant";
$x[]="Shamita";
$x[]="Tushar";
$x[]="UnniKrisnan";
$x[]="Vinita";
$x[]="Lal";
$x[]="Wamiq";
$x[]="Vishal";
$x[]="Yogesh";
$x[]="Zameel";

//Fetching varaibale s sent through xmlhttp object 
$s=$_GET["s"];

//if s>0, it will store the hints in the variable suggest
if (strlen($s) > 0)
{
$suggest="";
for($i=0; $i<count($x); $i++)
{
if (strtolower($s)==strtolower(substr($x[$i],0,strlen($s))))
{
if ($suggest=="")
{
$suggest=$x[$i];
}
else
{
$suggest=$suggest." , ".$x[$i];
}
}
}
}

// Show no suggestions,if nothing matches 
// or show the matched names 
if ($suggest == "")
{
$out="no suggestion";
}
else
{
$out=$suggest;
}

//output the response
echo $out;
?>

Output

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics