Official website for Web Designer - defining the internet through beautiful design
FOLLOW US ON:
Author: Steve Jenkins
15th October 2009

Build an AJAX search bar

THE SEARCH BAR HAS BECOME A FIXTURE OF MODERN WEB DESIGN

Build an AJAX search bar

THE SEARCH BAR HAS BECOME A FIXTURE OF MODERN WEB DESIGN. LEARN HOW TO MAKE YOURS STAND OUT USING AJAX AND JQUERY’S EFFECTS

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.

Author: Andy Leon | Originally appeared in Issue 159 | Download Tutorial Files

01 Design and slice
pic1
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”.

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

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” />
</div>

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() {.

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

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”).val(“”);
}
$(“#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”);
}
$(“#SearchResults”).slideUp();
});

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 });
$(“#SearchResults”).slideDown();

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(‘127.0.0.1’, ‘root’, ‘password’);
mysql_select_db(‘world’);
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;

Tags: , ,
  • Tell a Friend
  • Follow our Twitter to find out about all the latest web development, news, reviews, previews, interviews, features and a whole more.
    • http://batfan.com Batfan

      Very nice tut. Would prefer something more simple though (ie. storing the search terms in an XML file). Their just search terms so, I’m not sure they need the security or hassle of setting up a MySQL db.

    • http://ldfeeds.com Scott Madden

      Thanks for the wonderful article I have added a link to it in the Tutorials section on the sidebar of our site.

    • http://www.acleon.co.uk Andy Leon

      Hi all,

      It’s worth noting that this was part of a series and in an earlier part we had set up the Web server and PHP configuration. Back then, PHP had “magic_quotes_gpc” switched on by default. This escapes all incoming GET and POST variables to make them safe for database queries. This is no longer the case, so if your PHP config is not set up like this, you should use the mysql_real_escape_string() as part of Step 12.

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

      Andy

    • http://www.proedgedesign.com Kate

      Thanks, I will be adding this to my favorites.

      Cheers,
      Kate
      Atlanta Web Design

    • ling

      Where do you add the list of cities in the PHP file?

    • http://www.xpress-media.co.uk web design barnsley

      Nice tut, cheers I may use that in a up coming project

    • Pingback: Building an Ajax Search Bar | Andy Leon

    • http://www.lucaswelander.se Lucas Welander

      Hi, do you have any link or something similar but for ASP.NET? Ty for a nice article but if it were in asp.net it would be superb ;)

    • http://playnstop.com Free Watch Online Movies

      Thanks it’s great.i will use this script on my site.

    • IBU

      In the beginning of this tutorial it says “we’re going to be using the MySQL World Database, a sample database provided by MySQL that contains information on cities and countries”. I don’t see none of these files in your tutorials or the maybe clarification that we need to create these file by ourselves.

    • http://www.girltoys.se Vuxenleksaker

      Great tutorial! I will use it in one of my future projects.

    • ash

      in this how should i include ajax (the page should not refresh and the data should come directly when we enter)

      help textbox

      <?php
      //Make a MYSQL connection
      mysql_connect("localhost", "root", "") or die(mysql_error());
      mysql_select_db("Help") or die(mysql_error());
      //get all the data from unleashpm_overview table
      $name = $_POST['name'];
      $result = mysql_query("SELECT * FROM ajax_unleashpm_overview WHERE Question LIKE '%$name%'");
      //keeps getting the next row until there are no more to get
      while($row = mysql_fetch_array( $result )) {
      // Print out the contents of each row
      echo $row['Question'];
      echo '’;
      echo $row['answer'];
      echo ”;
      }
      ?>

    • Pingback: Build an AJAX search bar | Web Designer – Defining the internet through beautiful design » Web Design

    • Pingback: Create a search bar for your website « Adobe Help

    • Peter

      Great Tutorial!
      I would like to use some of this code on my page. When I type in the search box, the results are shown, and when I click on a result, the page refreshes and the search box has the default text.

      I want to be able to select one result and have it displayed in the search box. How do I do that? And without the page refreshing.

    • http://www.vippests.com/index.html mold removal in grants pass

      Hello mates, fastidious paragraph and nice arguments commented at this place, I
      am actually enjoying by these.

    • http://%URL% the text the romance back review

      Great article! We will be linking to this great article on our site.

      Keep up the good writing.

    • http://%URL% SMTP2GO Review

      Hi there friends, how is everything, and what you desire to say about this paragraph, in my view its
      actually remarkable in favor of me.

    • http://www.shawneenet.net/wp/?p=297 http://www.shawneenet.net/wp/?p=297

      I have read so many articles or reviews on the topic of the blogger lovers but
      this piece of writing is in fact a pleasant paragraph, keep it up.

    • http://www.10projectors.com/epson-powerlite-home-cinema-5020ub www.10projectors.com

      with brand new releases! Wow! Sound Terrific!Step 1 — Find a person’s Indiana Jones as well as Kingdom of your Crystal Mind Movie first you’ll be able to
      Search quite a few titles since you want, there tend to be no restricts.
      Browse many files in your favorite movie channels,
      television exhibits, sporting events plus more. Once
      you decide on what you are looking proceed to another location
      step.Step only two – Save Indiana Jones
      plus the Kingdom of this Crystal Cranium Movie, next Click on the file you only found to start your acquire.
      You will download Indy Jones and also the Kingdom in the Crystal Mind Movie
      and many other poker guides immediately. Your once membership fee will provide you
      with FREE DIGITAL VIDEO DISC Copy Computer software, Movie Competitors, CD Using up Software, VIP
      tech support team and further!Step 3 : Burn Indianapolis
      Jones and also the Kingdom of this Crystal Cranium Movie that will DVD.
      Play a newly saved movie using your pc, Home Live theatre, or Hdtv.
      The services provide you with the software necessary to easily shed your DISC Videos
      to help CD or perhaps DVD. Build the DVD motion picture collection.
      Join now and discover all you need to give to millions for user around the globe!
      Wow, isnt wonderful which you can watch it all the time, Yes!

      So will not wait now and find Ready to watch out and In Jones and also Kingdom in the Crystal Brain Movie Nowadays!

      Indispensable Lcd television AccessoriesLuce mannequin TV pores and skin look stand
      solely model and keep in various areas of a family
      home, plane as well as yacht. It can be an ultra small television with high quality
      PC. This standalone TV isn’t going to require another components. The a few parallel watching sources that Luce style offers usually are HDTV keep an eye on and hd monitor. The extensive aspect monitor format utilized for the product is highly worthy of DTV, DVD in addition to HDTV resource material.You will be able to view this kind of model inside bright light along with in almost any angle with the comfort of one’s room.

      This is realistic a result of wide experiencing angle
      and also high lumination level enjoyed by your monitor.
      The living quarters of your abode or office is usually augmented and living area can end up increased using
      the fence mounts. Wall supports of plasma tv set of LCD video are suitable with the aim.
      The benefits of using these units are a good number of.

      The unit will be wall attached with the various models of walls
      car without any flat solar panel. Gold plated attaches are utilized specially to
      get superior alert. 99. 95 p’cent oxygen absolutely free copper is required in the gps watch. The 1 metre greyish scat incorporated while in the unit provides you with affordable.Wall brackets are you can buy to meet on all sorts of wall space. They may carry some weight with 30 kgs. LCD home appliances are televisions, at days are given the small-scale tilt mount that is suitable intended for flat section televisions. The compact tilt offered on the market usually satisfies thirteen within . to twenty-four inch telly displays. Projector wall mounts too tend to be obtainable in the LCD home appliances are televisions.Mounts can be acquired for tv mount, wall support, screen support, desk position and threshold mount. Real hardwood veneer through safety goblet shelves tend to be attractive and provide a sensible look. Besides providing ample increasing space moreover it acts because storage designed for DVD’s,
      controllers along with other accessories with regard to gaming.
      They possess soft finishing doors. Enough fresh air is provided to make sure efficient
      operating from the device. Cable administration
      provided in your unit helps prevent clutter and keep your wires planned.
      The system features a good performance thanks to high top quality
      leads utilized for it. You will get high superior cables designed for speakers.
      It will let you enjoy a complete potential belonging to the device such as best
      smart quality not to mention vision. Decorative cable-trunking features are specially provided to cover speaker connections.
      A disguise of covered aluminium has the display cleaner.

      The clearer removes acne bacteria. However, it just isn’t advised to work with it upon flat screens because the alcohol together with sponge could harm the actual screen. The brand new innovation from the technology can be LC TV FOR PC phone, which are made for business individuals.They consist of two fast access to the internet, 2 SIM charge cards, touch computer screen, two video cameras, sliding display, micro SD position, memory minute card, GPRS, GSM, FAX, many wide variety of computer secrets, blue the teeth, television recorder, Email, television routine, movie participant and a variety of others.In house Antenna- Assistive Touch For Auto Tv AntennaI am certain that your hunt for indoor antenna has reach an end when you read this information. Yes, gone are days gone by when we must search forever for {backyard|interior|inside|indoors

    • http://ragecraftrc.net/profile.php?id=88301 ilex

      Tips on how to Select Ideal Projector

    • http://www.eurocasino-finland.com casinoeuro

      Have more From home Media With your Great Electronic devices!

    • http://wiki.sekine.com/index.php/%E5%88%A9%E7%94%A8%E8%80%85:Olga9212 liposuction dominican republic

      Every weekend i used to visit this web site, because i want enjoyment,
      for the reason that this this site conations really nice funny stuff too.

      Visit my wesbite at liposuction dominican republic