Languages you should know:
CSS
HTML
PHP
JavaScript
In this tutorial we will try to create a search suggest similar to Google
using AJAX technologies.
You can see the results of this tutorial will look like by typing a search
string in Google.
This tutorial will consis three files,
1. An HTML page for presenting the suggest search box
2. A JavaScript file for handling the AJAX
3. And a server side PHP script that will return the suggested searches.
Ok lets start.
Let say we are searching for a member in our site and let the members table is
created like this
CREATE TABLE 'members' {
'id' int(10) NOT NULL AUTO_INCREMENT,
'username' VARCHAR(255) DEFAULT NULL,
PRIMARY KEY ('id')
}
you can add as many values as you like. But in this tutorial we will only have
an id and a username just for example purposes.
In the uploaded file you can find the ajaxsuggest.sql file. You can just import
that file to MySql and see the results.
THE HTML
The HTML page is pretty straight forward. There is one form with a textbox for
entering the query a submitting button and a DIV that we will display our suggested
searches in.
<form id="fsearch" action="http://www.yourdomain.com/search.php">
<input type="text" id="tstSearch" name="txtSearch onkeyup="searchSuggest();" autocomplete="off" />
<input type="submit" id="btnSearch" name="btnSearch" value="Search" />
<div id="searchsuggest">
</div>
</form>
I guess the only new thing around here is the "autocomplete=off" command, this just stops browsers from
listing a set of terms that you have recently entered in the textbox.
The DIV with id="searchsuggest" is used to show the suggested items.
The DIV and some elements that we are going to be using in the future need some styling.
So we include a CSS file
<style type="text/css" media="screen">
body {
font: 11px arial;
}
.suggest_link {
background-color: #FFFFFF;
padding: 2px 6px 2px 6px;
}
.suggest_link_over {
background-color: #3366CC;
padding: 2px 6px 2px 6px;
}
#searchsuggest {
position: absolute;
background-color: #FFFFFF;
text-align: left;
border: 1px solid #000000;
}
</style>
THE JAVASCRIPT
Now it is time for Ajax stuff. We are going to place all our JavaScript code in an
external file called ajax_suggest.js.
The following function in the JavaScript envolves Ajax and it simply return a browser
specific XmlHttpRequest object.
// gets the browser specific XmlHttpRequest Object
function get_XmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Upgrade Your Browser");
}
}
The following variavle declaration createss our XMLHttpRequest object that will
be used to make the suggestion requests.
var ReqObj = get_XmlHttpRequestObject();
Now we wil create the function that actually make the AJAX requests.
// Called from keyup on the search textbox
//Starts the ajax request
function Suggest() {
if (ReqObj.readyState == 4 || ReqObj.readyState == 0) {
var str = escape(document.getElementById('txtSearch').value);
ReqObj.open("GET", 'searchSuggest.php?search=' + str, true);
ReqObj.onreadystatechange = handleSearchSuggest;
ReqObj.send(null);
}
}
As you can see in the form this function is called every time a key is pressed in the search textbox.
I think the above function is clear for a person who know JavaScript.
The first line is just to check if XMLHttpRequest object is ready to make a request.
The second line just get the value fomr the search text box and URL encodes it by
using the JavaScript escape function.
The next like opens the connection to our backend PHP page with the appended search
querystring and marks it as a "GET" request. We could pass this as a "POST", but since
security isn't an issue well leave it as a simple "GET".
The handleSearchSuggest function is called every time the state of our ReqObj XmlHttpRequest
object changes.
//called when the AJAX response is returned
function handleSearchSuggest() {
if (ReqObj.readyState == 4) {
var ss = document.getElementById('search_suggest')
ss.innerHTML = '';
var str = ReqObj.responseText.split("\n");
for(i=0; i < str.length - 1; i++) {
//Build our element string. This is cleaner using the DOM, but
//IE doesn't support dynamically added attributes.
var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
suggest += 'onmouseout="javascript:suggestOut(this);" ';
suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
suggest += 'class="suggest_link">' + str[i] + '</div>';
ss.innerHTML += suggest;
}
}
}
// mouse over function
function suggestOver(div_value) {
div_value.className = 'suggest_link_over';
}
// mouse out function
function suggestOut(div_value) {
div_value.className = 'suggest_link';
}
// click function
function setSearch(value) {
document.getElementById('txtSearch').value = value;
document.getElementById('searchsuggest').innerHTML='';
}
The above function is clear, the backend php will return suggestions separated with a newline,
this function just handles them.
And the rest two are very easy.
THE BACKEND PHP
Here is the php code
<?php
$link=mysql_connect('localhost','root','') or die (mysql_error());
$db_select = mysql_select_db("tutorial") or die (mysql_error());
if(!$db_select){
die("database selection failed" . mysql_error());
}
///Make sure that a value was sent.
if (isset($_GET['search']) && $_GET['search'] != '') {
//Add slashes to any quotes to avoid SQL problems.
$search = addslashes($_GET['search']);
$query = "SELECT distinct(username) as members FROM members WHERE username like('" .
$search . "%') ORDER BY username";
$result = mysql_query($query,$link);
if(!$result){
die("database failed " . mysql_error());
}
while($suggest = mysql_fetch_array($result)) {
echo $suggest['members'] . "\n";
}
}
?>
Well the above code is really simple, it just return the suggested items in array concatinated with a new line!
now that we are done try searching se7en in the search box.
I hope you enjoy this tutorial.