The single most important power every web-developer should give to the users is the ability to search for data. With millions of blogs and sites coming up everyday, users simply find themselves lost in the ocean of data. Then comes the power of the tiny search-box. And how about an animated ajax search that further stops the user from waiting to load another page? Interesting? Then, read on!
Download Source Try Demo

Build the Layout

First things first: we build the layout. Since this is just an example of how things work, we are not going to make it very attractive; rather it would have a basic structure.
Create an index.php file and put the following code inside it.
<html>
<head>
<title>Ajax Search With jQuery</title>
<link rel='stylesheet' href='style.css'></link>
<script type='text/javascript' src='jquery.pack.js'></script>
</head>
<body>

<div id='container'>
<div id='search-box'>
 <span id='search-text'>Search</span>
 <form id='search-form'>
  <input type='text' id='input-text' name='s' value='Type and hit enter'/>
 </form>
</div>

<div id='results'>

</div>

</div>

</body>
</html>
Pretty simple to follow. We added jQuery and style.css. We made a container within which the search-box and results are placed. The results will be shown as list items (i.e. <li> elements).

Now, we create a style.css file and put the following css there.
html, body, div, h1, h2, h3, h4, h5, h6, ul, ol, dl, li, dt, dd, p, blockquote,
pre, form, fieldset, table, th, td { margin: 0; padding: 0; }
body {
 font-size:14px;
}
a, a:visited {
 color:blue;
}
#container {
 width:480px;
 margin:auto;
}
#search-box {
 width:233px;
 height:42px;
 background: url("images/search-form.png") no-repeat center;
 margin:15px auto;
}
#search-text {
 float:left;
 background:#000000;
 width:58px;
 margin:2px;
 color:#ffffff;
 padding:11px 0px;
 text-align:center;
}
#search-text a {
 color:#ffffff;
}
#search-form {
 margin:0px;
 padding:8px 0px;
 display:block;
}
#search-form #input-text{
 background:transparent;
 border:0px;
 margin:3px;
 font-size:1.1em;
}
#search-status {
 border:1px solid #ebeef5;
 padding:6px;
}
#results ul {
 list-style:none;
 margin:15px 0px;
 padding:0px;
}
#results ul li {
 padding:5px 5px 5px 18px;
 margin-bottom:15px;
 border-top:1px solid #ebeef5;
 border-bottom:1px solid #ebeef5;
}
#results ul li a {
 text-decoration:none;
}
The first part of the code is stolen from NetTUTS! You can find the image: search-form.png along with the source code given with this tutorial. The css is pretty simple and easy to understand. Only one thing I'd like to mention: notice that we have set the background of #input-text to transparent even though it comes above the search-box (whose background is already set). This is because if we have not done so, the default background in <input&t; elements (which is white) will be visible.

If you have done it right, you should have this:


Prepare the database

Now that we have prepared our layout, it's time we move in the back-end and set up the database and work with PHP.


We create a simple table in the database. The table needs not be the same as it is shown here. It can have other fields. For this simple tutorial, I created this simple table.

Here, we have only 3 fields: id, title & url. (We are going to search the title field only.)

Then we add some dummy data to the table.


Connect To The Database

We create a config.php file and put the following codes in it.

<?php
$hostname = "YOUR_HOSTNAME";
$username = "YOUR_USERNAME";
$password = "YOUR_PASSWORD";
$database_name = "YOUR_DATABASE_NAME";

$link = mysql_connect($hostname, $username, $password) or die("Cannot connect to the database!");
mysql_select_db($database_name) or die("Cannot select the database!");
?>
Here we just made a connection with MySQL database. Change the default values with your own credentials.

Show the Data

Now, we have the database prepared and we are able to connect to the database. Now, we show the data in index.php page. We include the config.php file in index.php by adding these lines of code at the top of index.php


<?php
include("config.php");
?>
Now, we have access to the database connection. Thus, we add the following lines inside the results div of index.php
<ul>
<?php
$q = "SELECT * FROM posts";
$r = mysql_query($q);
while($row = mysql_fetch_assoc($r))
 {
?>
<li><a href='<?php echo $row['url']; ?>'><?php echo $row['title']; ?></a></li>
<?php
 }
?>
</ul>
Here we create an ul element and then query the table to get a resultset of all the rows. Once we have the resultset, we loop through all the rows and create a li element for each row. Note that we wrapped the title with the corresponding url of the row.

Add Some Effects

Now, we make an ajax call to search.php (which we will create in the next step) and make an animated effect while the request is being sent.

<script type='text/javascript'>
$(function(){
/* This is the jQuery section
 * All javascript codes in this tut go here
 */
 $("form#search-form").submit(function(){
  $("#search-form").hide();
  $("#search-text").animate({"width":"229px"});
  $("#results").fadeOut();
  $.ajax({
   type:"GET",
   data: $(this).serialize(),
   url: "search.php",
   success: function(msg)
    {
    $("#results").html(msg);
    $("#results").fadeIn();
    $("#search-text").html("<a href='#' id='search-again'>Search Again</a>");
    }
  });
 return false;
 });
</script>
The above bit of codes goes within the index.php file after we added jquery. Follow the code closely. Here, we add a function that works only when the search form is submitted. When the form is submitted, we simply hide the form and set the width of #search-text to 229px (which is the total width of search-box div) with a cool animation, thanks to jQuery. Then, we make an ajax call to search.php (which we will create in the next step) and put the response from search.php in results div and fade in the results div. To stop the page from reloading we add return false. But since we have already set the width of search-text div to 229px and have hidden the form, the form is no longer available. But the user may again need to search. So, we add a link (with title "Search Again") to let the user access the form again. Thus we again add the following bit of javascript just after the above lines of codes.
$("#search-again").live("click", function()
  {
   $("#search-text").html("Search");
   $("#search-text").width("58px");
   $("#search-form").fadeIn();
  });
Two things to notice: first, we make use of the live() function of jQuery (new in jQuery 1.3.1). That's because this function repeatedly binds elements to future events; you don't have to bind it again and again. Secondly, we set the width of #search-text to 58px. This is exactly the width of the #search-text as set by css. To make the long story short, we bring back the earlier form when "Search Again" is clicked.

Search it, baby!

Finally, we create the main search.php file. We add the following lines of code in search.php

<?php
include("config.php");
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING);
$q = "SELECT * FROM posts WHERE title LIKE '%".$search_term."%'";
$r = mysql_query($q);
if(mysql_num_rows($r)==0)//no result found
 {
 echo "<div id='search-status'>No result found!</div>";
 }
else //result found
 {
 echo "<ul>";
 while($row = mysql_fetch_assoc($r))
  {
  $title = str_ireplace($search_term, "<b>".$search_term."</b>", $row['title']);
?>
 <li><a href='<?php echo $row['url']; ?>'><?php echo $title ?></a></li>

<?php
  }
 echo "</ul>";
 }
?>
Here, we include config.php file to get access to the database connection. Then, we 'sanitize' the search term with filter_var (available in PHP 5.2+). Next, we search all the titles in the table that matches the required search term. If result(s) is (are) found, we loop through the resultset, and wrap the search term with <b> tag. We, then, create a list element for each result.

Conclusion

This is simple search tutorial. It mainly focuses on jQuery's ajax techniques and effects you can create with it. You can implement this technique in your Wordpress blog and create something like the legendary K2.

Labels: , ,

blog comments powered by Disqus
Blogger Steven said...
Its a great concept, but is messed up in Firefox 3 (works in IE8) therefor your CSS is way off. And the PHP takes off to a blank page that seems to sit loading (Firefox again).
Blogger Abhisek said...
Hi Steven! There's no problem with CSS. I think you have commented on the basis of the demo provided with the tutorial. The demo is NOT working. It's a free hosting facility I was availing. Looking forward to buying my own domain. Try setting up in your local server; there won't be any problem. :)