Thursday, March 18, 2010

Use JQuery to make an AutoSuggest box in PHP - a Tutorial

At times it's easiest to wire up your own ajax page with a sprinkle of XMLHttpRequest() here and .readystatechage there. Other times, it's pretty handy to use a well packaged library, like jQuery, where most of the heavy lifting has been done for you.

Let's say you have two simple pages

search.html









which, when you type in some text into "namesearch" and click "search" will POST to the page

results.php



<?php
$name = $_POST["name"];
$con = mysql_connect("localhost","root","");
if (!$con){ die('Could not connect: ' . mysql_error());}
mysql_select_db("friendface", $con);
$result = mysql_query("SELECT * FROM users where name like" . " '%" . $name . "%'");
//output the results to an unordered list
echo "
    ";
    while($row = mysql_fetch_array($result)) {
    echo "
  • ".$row['name']."
  • ";
    }
    echo "
";
mysql_close($con);
?>



so, when you type something into the search field



and click submit you see a list



Now, if you want to have the results show up below the search bar, just drop in a reference to jQuery in the header.


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>


Now, let's fire a function in the "onkeyup" event from the search box:





which will call a javascript funtion "suggest" and pass it the value of the textbox. Now, we have to let the page know what that function should do. What we want it to do is to call the results page, get the results, and display them on the page. All using Ajax.

So, let's make a <div> area for the results to be displayed. place the following after the button





which gives the page a div to drop some results into, and back up in the header, let's make out js function.




so by this point, your whole page should look like this

search.html



Now, when you type int he text box you should get the results showing up just below the search field.

Of course, it would be nice to pretty it up a bit. Add a line in the head section

<link type="text/css" href="style.css" rel="stylesheet" />


create a new file

style.css



#namesearch{
padding:3px;
border:1px #CCC solid;
font-size:17px;
}
#suggestionList {
margin: 0px;
padding: 0px;
height:20px;
width: 200px;
font-size:16px;
font-family:Arial, Helvetica, sans-serif;
color:#333;
padding:5px;
margin-bottom:10px;
}
#suggestionList ul li {
list-style:none;
margin: 0px;
padding: 6px;
border-bottom:1px dotted #666;
cursor: pointer;
}
#suggestionList ul li:hover {
background-color: #FC3;
color:#000;
}
ul {
font-family:Arial, Helvetica, sans-serif;
font-size:11px;
background-color:#000;
color:#FFF;
padding:0;
margin:0;
}


and reload your page. Lovely.

No comments:

Post a Comment