Notice: Undefined index: order_next_posts in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 194

Notice: Undefined index: post_link_target in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 195

Notice: Undefined index: posts_featured_size in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 196

Build an AJAX search bar



CREATING AN EFFECTIVE search bar can be tricky. There are lots of features that have become pretty widespread but are difficult to implement. We’re going to create a bar that
has it’s own custom button that integrates with the bar, slidedown live results from an AJAX script and a helper hint that vanishes when you come to use the search bar. As the basis
for our searching, we’re going to be using the MySQL World Database, a sample database provided by MySQL that contains information on cities and countries. We’re going to use this to
create an city search for a travel agent-style website.

01 Design and slice
In Photoshop, create your search box. We made a box with a single pixel border, inner and outer shadows. We then overlaid an icon of a magnifying glass that will be our button. We
then slice it into two images and save them as “search_box.png” and “search_button.png”.

02 Create the HTML doc

Open Dreamweaver and start a new HTML document. Make sure the encoding is set to UTF-8 so that the various extended characters that make up the names of foreign cities are
rendered correctly. Insert a <form>, with a <table> inside, and add two <div> tags with IDs “SearchBox” and “SearchButton”.

<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8”>
<form action=”” method=”post”>
<table style=”margin: auto; width: 975px;”>
<img src=”images/logo.png” />
<td width=”380”>
<div id=”SearchBox”>
<input id=”SearchInput” name=”SearchInput” value=”City Search” />
<div id=”SearchButton”>
<input type=”image” src=”images/search_button.png” />

03 Style Divs
In the style section of your document, style the first <div> to show your search box image.
Set the “height” and “weight” attributes of both to match those of the images. Set the
“float” attribute to “left” so that they line up left-to-right. Add an <input> tag with type
“image” and the “src” attribute set to your button image.

#SearchBox {
background: url(‘images/search_box.png’);
float: left;
height: 60px;
width: 305px;
#SearchButton {
float: left;
height: 60px;
width: 70px;

04 Add an input box
Add an <input> tag inside the “SearchBox” <div> so that the user can enter the text they want to search for. Set the “name” and “id” attributes to “SearchInput” and the “value”
attribute to “City Search” – this will appear when the page loads so the user knows what the search box is for.

<div id=”SearchBox”>
<input id=”SearchInput” name=”SearchInput” value=”City Search” />

05 Style the input box
Now style “SearchInput” so that it blends in with the images. Set the “background” and “border” attributes to none so they don’t show. Increase the font size so it matches the size of the image and then adjust the margins to centre it. Set the “outline” property to “none” in order to get rid of that blue glow that some browsers add when you click into an input box. Finally, change the “color” attribute to a light grey so your “City Search” hint text doesn’t look like search text.

#SearchInput {
background: none;
border: none;
color: #999999;
font-size: 16px;
outline: none;
margin: 20px;
width: 280px;

06 Add search results
Add another row to the table and place a <div> tag in the cell underneath your search box to hold your search results. For the best browser compatibility, add another <div> inside
this one, which has the ID “SearchResults”. You can then style the inner div to float over the top of the rest of your content and use relative positioning on the outer div to bring it close to your search box.function repeater() {.

<div style=”position: relative; left: 20px; top: -48px;”>
<div id=”SearchResults”></div>

07 Style the search results
Style your “SearchResults” <div> by adding a “background” and “width” attribute. You need to set the “position” and “z-index” attributes so it floats above other content. Set the “overflow” attribute to “auto” so that it will expand to fit however many search results there are. Finally, set the “display” attribute to “none” so that it’s hidden when the page loads.

#SearchResults {
background: #000000;
display: none;
overflow: auto;
position: absolute;
width: 330px;
z-index: 99;

08 Focus
Now your structure’s in place, you can start adding some JavaScript, starting with the focus event, which fires when the user clicks or tabs into your search box. You only want to do
two things here – remove the “City Search” text if it’s there, and change the CSS “color” property so that the user is typing in black.

$(“#SearchInput”).focus(function() {
if($(“#SearchInput”).val() == “City Search”) {
$(“#SearchInput”).css(“color”, “#000000”);

09 Blur
The opposite of focus is the blur event. In this function, check to see what the value of the “SearchInput” box is. If there’s nothing there, add the “City Search” text back in and change the CSS “color” property back to light grey. Finally, use jQuery’s slideUp() function to hide search results if they’re showing.

$(“#SearchInput”).blur(function() {
if($(“#SearchInput”).val() == “”) {
$(“#SearchInput”).val(“City Search”);
$(“#SearchInput”).css(“color”, “#999999”);

10 Catching key presses
Your third function is attached to the keydown event and is used for trapping keyboard actions. Your event comes through as “e”, and you can use the “which” property to identify which key was pressed. Test the “which” property for the value 8 (corresponding) to the backspace key. If this is the case, trim one character off the end of the search text, for all other cases add the character corresponding to that key code. Then call our AJAX page through the load() function, putting the results in your SearchResults <div>. Then call the slideDown() function, to make sure your results are showing.

$(“#SearchInput”).keydown(function(e) {
if(e.which == 8) {
SearchText = $(“#SearchInput”).val().substring(0, $(“#SearchInput”).val().length-1);
else {
SearchText = $(“#SearchInput”).val() + String.fromCharCode(e.which);
$(“#SearchResults”).load(“ajax.php”, { SearchInput: SearchText });

11 Create our AJAX script
Create a new PHP document and save it as “ajax.php”. Call the necessary mysql_connect() and mysql_select_db() functions to get access to the database tables. Then check to make sure that you’ve got “SearchInput” in the $_POST array and put that in a variable called $SearchInput, converting it all to lowercase as you do so.

mysql_connect(‘’, ‘root’, ‘password’);
if(isset($_POST[‘SearchInput’])) {
$SearchInput = strtolower($_POST[‘SearchInput’]);

12 Run the query
Use your $SearchInput variable to construct a query that searches through the database and brings you your results. In this query you’re using a descending sort on the Population field with a limit of ten. This way, when searching you’ll only get the ten biggest cities that match our search text.

$Cities = mysql_query(‘select * from City where Name like “%’.$SearchInput.’%” order by Population desc limit 10’);

13 Step through the results
Then use the mysql_fetch_assoc() function to step through the results and output them as <a> links, but there’s more to do inside this loop. You need to use utf8_encode() on the city name to cope with foreign characters. Also use str_replace to wrap each occurrence of your search text in a <span>, with the class “highlight”. Do this twice, the second time using the ucfirst() function to preserve any capital letters. Finally, add a comma and the country code to the end.

while($City = mysql_fetch_assoc($Cities)) {
$Name = utf8_encode($City[‘Name’]);
$Name = str_replace($SearchInput, ‘<span class=”highlight”>’.$SearchInput.’</span>’, $Name);
$Name = str_replace(ucfirst($SearchInput), ‘<span class=”highlight”>’.ucfirst($SearchInput).’</span>’, $Name);
$Name = $Name.’, ‘.$City[‘CountryCode’];
echo ‘<a href=””>’.$Name.’</a>’;

14 Add the highlighting
Finally, add some additional styling to your HTML page so that the “highlight” class is displayed in blue. This means that your search text shows up in your results. It’s up to you what to do with the search results once you’ve got them. Change the “action” attribute of the <form> to provide a search page or change the “href” attributes of the <a> tags in our “ajax. php” file.while($City = mysql_fetch_assoc($Cities)) {. The full code for this step can be found on the cover disc, titled step14code.txt. We’ve included a snippet below for reference.

#SearchResults a {
color: #FFFFFF;
display: block;