Imitate Google suggest with Ajax and php
- by phil
I want to imitate Google suggest with the following code, which means:
step 1: When user types in search box, the query string will be processed by a server php file and query suggestion string is returned(using Ajax object).
step 2:When user clicks on a query suggestion, it will fill into the search box (autocomplete).
Step 1 is achieved while step 2 is not. I think the problem lies in the .click() method. My intention is to use .click() binding a onclick event to the dynamically created <li> element. Any idea?
<script src="jquery-1.4.2.js">
</script>
<style>
#search,#suggest,ul,li{margin: 0; padding:0; width: 200px;}
ul{ list-style-type: none;}
.border{border: solid red 1px; }
</style>
<p>My first language is:</p>
<input type="text" width="200px" id="search" onkeyup="main(this.value)" value="" />
<ul id="suggest"></ul>
<script type="text/javascript">
function main(str)
{
//setup Ajax object
var request=new XMLHttpRequest();
request.open("GET","language.php?q="+str,true)
//core function
request.onreadystatechange=function()
{
if ( request.readyState==4 && request.status==200)
{ if (str=="") {$('li').remove(); $('ul').removeClass('border');return;}
$('li').remove();
array=request.responseText.split(",");
for (i=0;i<array.length;i++)
{
//create HTML element of <li>
$('#suggest').append($('<li>',{id: 'li'+i, html: array[i]}));
//style ul
$('ul').addClass('border');
//I THINK HERE IS THE PROBLEM!
$('li'+i).click(function(){ $("#search").html(array[i]);});
}
}
}
request.send();
}
</script>
PHP:
<?php
$q=$_GET[q];
$a[]='english';
$a[]='chinese';
$a[]='japanese';
$a[]='eeeeee';
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>