In this tutorial I will show you how to create an AJAX search box that can be used on your website or blog that also has an integrated Google search built in. We will be using HTML, CSS, PHP and jQuery to create our search box.

Preperation

There is quite a lot of code in this tutorial so I am only going to cover the essential bits. To see the full code either go to the demo and “view source” to see how it was done or download the ZIP file with the source code. Anyway lets get started. First off some preperation.

Don’t worry thats all we need.

1) The HTML

Now in the HTML head include our new javascript files. The jQuery file and a file imported from Google to power the Google search.

<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script src="http://www.google.com/jsapi?key=YOURAPIKEY" type="text/javascript"></script>

Remember to place your API key in there. The main content of the HTML file should be as follows:

<div id="searchbox">
    <h1>Want to find something?</h1>
    <input type="text" id="search" value="Search..." autocomplete="off" />
    <div id="resultbox" style="display:none;">
        <div class="siteheader"></div>
        <div id="sitesearch"></div>
        <div class="googleheader"></div>
        <div id="googlesearch"></div>
    </div>
</div>
<div id="footer">
    Copyright &copy; 2008 My Company Inc
</div>

So what do we have here. Basically an input box (note no form tags) with an id and a value and the “autocomplete” parameter set to “off”. This is to stop the standard autocomplete box showing when you type stuff into the box. We then have a “resultbox” div (which is initially hidden) with 4 other divs. As you can see each type of search has 2 divs: a header and body div. If you were wanting to add other types of search here (like a yahoo search for instance) you can just add more divs as needed. And last but not least a footer (which is not required but I liked it). Not too complex huh.

2) The Javascript

Now this is where the fun starts. In your page head just after you have included the two javascript files add the following:

<script language="Javascript" type="text/javascript">
//<![CDATA[
google.load("search", "1");
 
$(document).ready(function() {
	$("#search").blur(function () {
		if($(this).val() == ""){
			$(this).val("Search...");
			$("#resultbox").css("display", "none"); 
		}
	});
 
	$("#search").focus(function () {
		if ($(this).val() == "Search...") {
			$(this).val("");
		}
	});
 
	$("#search").keyup(function () {
		$("#resultbox").css("display", ""); 
		$("#footer").css("display", "none");
		$(".siteheader").html('<img src="images/loading.gif" width="16" height="16" style="margin-right:8px; vertical-align:-15%;" />Loading Results from Site...');
		$(".googleheader").html('<img src="images/loading.gif" width="16" height="16" style="margin-right:8px; vertical-align:-15%;" />Loading Results from Google...');
 
		/* === Site Search === */
		$.ajax({ 
			method: "get",
			url: "sitesearch.php",
			success: function(html){  
				$(".siteheader").html('Results from Site:');
				$("#sitesearch").html(html); 
			}
		});
 
		/* === Google Search === */
		var sc = new GSearchControl();
 
		sc.addSearcher(new GwebSearch());
		sc.addSearcher(new GvideoSearch());
		sc.addSearcher(new GblogSearch());
		sc.addSearcher(new GnewsSearch());
 
		var drawOptions = new GdrawOptions();
		drawOptions.setDrawMode(GSearchControl.DRAW_MODE_TABBED);
 
		var foo;
		sc.setSearchCompleteCallback(foo, function(){
			$(".googleheader").html('Results from Google:');
		});
 
		sc.setNoResultsString(GSearchControl.NO_RESULTS_DEFAULT_STRING);
 
	    sc.draw(document.getElementById("googlesearch"), drawOptions);
		sc.execute(document.getElementById("search").value);
		/* === End Search === */
 
		if($(this).val() == ""){
			$("#resultbox").slideUp(700, function(){
				$("#footer").css("display", "");
			});
		}
	});
});
//]]>
</script>

“Wow” I hear you saying. Don’t worry I will explain what all of this does, but before I do I recommend you read through the code a few times and get a feel for it as it will help you understand it when I explain it.

Ok lets start off simple. The first line loads the Google search.

google.load("search", "1");

The next bit of code controls how the search box itself works. Basically if the search is blurred (ie you are not using it) and there is nothing in the box then it makes the value of the search box “Search…” and hides the result box. Simply resetting it. If you focus the search box, however, and the value is “Search…” it hides the word “Search…”.

$("#search").blur(function () {
    if($(this).val() == ""){
        $(this).val("Search...");
        $("#resultbox").css("display", "none"); 
    }
});
 
$("#search").focus(function () {
    if ($(this).val() == "Search...") {
        $(this).val("");
    }
});

The next part is defining the keyup event. What we are doing here is every time you release a key we are going to update the search. “Why not keydown?” I hear you ask. Well if you use keydown it will search the last value you entered and not the current one. Try it out to see what I mean.

$("#search").keyup(function () {
//...
});

So a few things need to happen once we have triggered the keyup event. Frist we need to display the resultbox div. Second, in this example, I hide the footer but if you don’t have the footer then miss this bit out. Third we set the HTML in our siteheader and google header divs. Basically this is just a loading image with some loading text.

$("#resultbox").css("display", ""); 
$("#footer").css("display", "none");
$(".siteheader").html('<img src="images/loading.gif" width="16" height="16" style="margin-right:8px; vertical-align:-15%;" />Loading Results from Site...');
$(".googleheader").html('<img src="images/loading.gif" width="16" height="16" style="margin-right:8px; vertical-align:-15%;" />Loading Results from Google...');

Next we are going to actually do our site search. This is simply an AJAX request (using jQuery of course) to a file called “sitesearch.php”. In this example our sitesearch.php file returns dummy data but in the real world this would search your website database and return the results. I’m not going into this in this tutorial as that is a tutorial in itself. Once the request is complete we update the siteheader and sitesearch divs with the appropriate content.

/* === Site Search === */
$.ajax({ 
    method: "get",
    url: "sitesearch.php",
    success: function(html){  
        $(".siteheader").html('Results from Site:');
        $("#sitesearch").html(html); 
    }
});

The next thing we need to do is the actual Google search. I wont go into this in too much detail as you can read Google’s own documentation to see what options there are.

  • Create a new “GSearchControl”.
  • Add different types of searches to the control. Its up to you what you want to include here.
  • Set the “drawOptions” to Tabbed.
  • Set our “searchCompleteCallback”. In here we just set the googleheader div to show appropriate content.
  • Set the “NoResultsString” to default and set which element to draw our results to (the googlesearch div).
  • Finally execute the search using the value from the search box
/* === Google Search === */
var sc = new GSearchControl();
 
sc.addSearcher(new GwebSearch());
sc.addSearcher(new GvideoSearch());
sc.addSearcher(new GblogSearch());
sc.addSearcher(new GnewsSearch());
 
var drawOptions = new GdrawOptions();
drawOptions.setDrawMode(GSearchControl.DRAW_MODE_TABBED);
 
var foo;
sc.setSearchCompleteCallback(foo, function(){
    $(".googleheader").html('Results from Google:');
});
sc.setNoResultsString(GSearchControl.NO_RESULTS_DEFAULT_STRING);
 
sc.draw(document.getElementById("googlesearch"), drawOptions);
sc.execute(document.getElementById("search").value);

The final part of our javascript code is some cleaning up. Simply if you delete all the characters in the search box we will close the result box (using some jQuery animation) and show the footer.

if($(this).val() == ""){
    $("#resultbox").slideUp(700, function(){
        $("#footer").css("display", "");
    });
}

And thats our javascript. I’ll let you take a break before we move on.

3) The CSS

I’m not going to say to much about the CSS as most of it is just standard styling. There is nothing fancy happening. There are a few style hacks for the google search but that’s about it. The main part of the CSS file looks like the following:

#searchbox {
	margin:0 auto;
	background:url(images/back.png) no-repeat top; 
	width:700px; 
	height:200px; 	
	margin-top:100px;
	padding:40px 0px 0px 40px;
	color:#fff;
}
#resultbox {
	border: 3px solid #999;
	background:#fff;
	padding:15px;
	width:620px;
	margin-top:5px;
	margin-bottom:10px;
	color:#000;
}
#footer {
	margin:0 auto;
	width:700px; 
	color:#999;
	padding-left:40px;
	margin-top:-25px;
}	
 
input {
	font-family:Georgia;
	font-weight:bold;
	font-style:italic;
	padding:10px;
	font-size:20px;
	border: 3px solid #ccc;
	width:630px;
}
 
input:focus,
textarea:focus,
select:focus {
  border: 3px solid #999;
}
 
#googlesearch, #sitesearch {
	margin-left:20px;
}
 
.googleheader, .siteheader {
	font-size:18px;
	font-family:Georgia;
	font-weight:bold;
	font-style:italic;
	margin:20px 0px;
	border-bottom:1px solid #ccc;
	color:#666;
}
.siteheader {
	margin-top:5px;
}
 
/* Google Style Hacks */
.gsc-search-box, .gsc-configLabelCell {
	display:none;
}
.gsc-control {
	width:100%;
}
 
.gsc-tabHeader {
	padding:3px 8px 5px 8px;
}
.gsc-tabhActive {
	border-top:2px solid #666 !important;
}
.gsc-tabhInactive {
}
 
/* Link Colour */
#resultbox a, .gs-title, .gs-title b {
	font-size:13px;
	font-weight:bold;
	color:#2253AA !important;
}
.gs-visibleUrl, .gs-visibleUrl-short {
	color:#666 !important;
}

To see the full CSS file download the source code.

Conclusion

And that is us. We have created an AJAX search with an Integrated Google Search to really help our users find what they are looking for. As always this is very flexible and this tutorial is only an example of what you can do. Let me know if you come up with any creative alternatives and post them in the comments.

View the Demo Download the ZIP file

Related Posts

More?

If you enjoyed this post, please consider promoting it.
  • Digg
  • del.icio.us
  • StumbleUpon
  • Design Float
  • Reddit
  • Mixx
  • Technorati

Remeber to subscribe to the feed and get future articles delivered to your feed reader.

If you want to discuss this tutorial or any other thoughts you have then you can do so over on our fourm.

Comments

  1. Comment by mr.ak09 on January 20, 2009 4:34 am

    hi i use ur script its works but i have one problem ?can help me about video conferencing using php langauage.if u have any idea about this plz share with me

Leave a Comment

(required)

(required)