How to make a basic live search using PHP and AJAX

How to make a basic live search using PHP and AJAX


In this tutorial I will show you how to make a simple live search using PHP and AJAX similar to the one used on this site and Google.

You have probably seen on the Google homepage, that when you start typing, Google suggests results that have previously been searched for. A simple version of this can be achieved using PHP and AJAX, and I will show you how to use this in a simple search form on a news page.

For this tutorial you will need a basic understanding of PHP, MySQL and an understanding of javascript will help.

This tutorial will use 3 files: livesearch.html, livesearch.js and livesearch.php.

For each of these files I will show the code then go through it and try and explain what is happening as much as I can.

Firstly you will need to set up a MySQL with the following format:

CREATE TABLE IF NOT EXISTS `news` (
`newsID` int(11) NOT NULL auto_increment,
`newsTitle` varchar(100) NOT NULL,
`newsContent` text NOT NULL,
PRIMARY KEY (`newsID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=10 ;


This will set up a table with 3 fields newsID to store a reference for each news article, newsTitle to store the title of the news article and newsContent to store the articles content.


livesearch.html


<html>
<head>
<title>My AJAX Search</title>
</head>
<body>
<form id="quick-search" action="../search" method="post" >
<p>
<label for="qsearch">Search:</label>
<input id="qsearch" type="text" name="qsearch" onkeyup="liveSearch()" />
<input type="submit" />
</p>
<ul id="searchResults">
</ul>
</form>
</body>
</html>


This is basically the form where the user will input the search text. Nothing special here other than the 'onkeyup="liveSearch()"' this will cause the function liveSearch() everytime the user releases a key. Also note the '<ul id="searchResults"></ul>' this is where we will return our results.


livesearch.js


function createRequestObject(){
var request_o;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_o = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_o = new XMLHttpRequest();
}
return request_o;
}

var http = createRequestObject();

function liveSearch()
{
var url = "livesearch.php";
var s = document.getElementById('qsearch').value;
var params = "&s="+s;
http.open("POST", url, true);

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {
if(http.readyState == 4 && http.status != 200) {
document.getElementById('searchResults').innerHTML='<li>Loading...</li>';
}
if(http.readyState == 4 && http.status == 200) {
document.getElementById('searchResults').innerHTML = http.responseText;
}
}
http.send(params);
}

function sendToSearch(str){
document.getElementById('qsearch').value = str;
document.getElementById('searchResults').innerHTML = "";
}


Ok, I will break this code down bit by bit as there is alot here to swallow.


function createRequestObject(){
var request_o;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_o = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_o = new XMLHttpRequest();
}
return request_o;
}


This first chunk is actually pretty much all 'AJAX' is, this is the way we connect to the backend PHP file on the fly. The 'XMLHttpRequest' function allows javascript to communicate with the server without changing page or reloading the page - fantastic!


var http = createRequestObject();


Here we assign the request object to the variable 'http' ready to be used later on.

The next chunk is a big one so I'll break it down even more.

function liveSearch()
{
var url = "livesearch.php";
var s = document.getElementById('qsearch').value;
var params = "&s="+s;
http.open("POST", url, true);

Here we declare our variables and assign the information. Firstly we assign the url we are sending the information to, in our case 'livesearch.php' in order to connect to this url we use the .open function, note this is put after http (which was our request object), for this tutorial the only important thing is the 2nd argument 'url' as this is the variable of the url we are sending our information to.


http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

This is a personal preference of mine this just makes sure the browser sends the information in the correct format and avoids a few errors.


http.onreadystatechange = function() {
if(http.readyState == 4 && http.status != 200) {
document.getElementById('searchResults').innerHTML='<li>Loading...</li>';
}
if(http.readyState == 4 && http.status == 200) {
document.getElementById('searchResults').innerHTML = http.responseText;
}
}
http.send(params);
}

This means that whenever the state of the information being returned changes, the onreadystatechange function is executed. A few examples of the different ready states are 'complete' and 'connecting' but these readystates are assigned to numbers within the javascript code. A 'complete' ready state has a code of 4, we are not error checking for anything else in this tutorial so this is the only code which is important. the status function is a nice addition which lets us know when the requested data has loaded. The 'loaded' code is 200, so when the readystate is 4 and the status is 200 we know a connection is made and we can collect our data.


document.getElementById('searchResults').innerHTML = http.responseText;


This line will take the information we send back from the PHP function to the searchResults <li> we assigned earlier.

livesearch.php

<?php
//database connections
$hostname = "########";
$user = "#########";
$pass = "###########";
$database = "##########";

$connection = mysql_connect($hostname, $user, $pass) or die(mysql_error());
mysql_select_db($database, $connection) or die(mysql_error());

$s = $_REQUEST["s"];
$output = "";
$s = str_replace(" ", "%", $s);
$query = "SELECT * FROM news WHERE newsContent LIKE '%" . $s . "%'";
$squery = mysql_query($query);
if((mysql_num_rows($squery) != 0) && ($s != "")){
while($sLookup = mysql_fetch_array($squery)){
$displayName = $sLookup["newsTitle"];
$output .= '<li onclick="sendToSearch(\'' . $displayName . '\')">' . $displayName . '</li>';
}
}

echo $output;
?>


Again, this code is quite a chunk so I will break it down into manageable chunks.

<?php
//database connections
$hostname = "########";
$user = "#########";
$pass = "###########";
$database = "##########";

$connection = mysql_connect($hostname, $user, $pass) or die(mysql_error());
mysql_select_db($database, $connection) or die(mysql_error());

This is simply the code to connect to your database, you will need to replace the '#######' with your database information.


$s = $_REQUEST["s"];
$output = "";
$s = str_replace(" ", "%", $s);
$query = "SELECT * FROM news WHERE newsContent LIKE '%" . $s . "%'";
$squery = mysql_query($query);

First we get the search parameter sent from the javacript code. We then replace all spaces with a % character (in PHP this is the wildcard character, there are many advantages to this and will return more search results when users type into the textbox.
We then query the database for any news article whos content has the selected search terms in.



if((mysql_num_rows($squery) != 0) && ($s != "")){
while($sLookup = mysql_fetch_array($squery)){
$displayName = $sLookup["newsTitle"];
$output .= '<li onclick="sendToSearch(\'' . $displayName . '\')">' . $displayName . '</li>';
}
}

echo $output;
?>

Finally, we check that the query is not blank and there is at least 1 row returned, if both these values are met we output the tutorial title in the output box. Note the 'sendToSearch' function when the user clicks this link, this is a basic javascript function we set in our .js file which simply takes the content of the <li> you clicked and places it in the search box.

That's all for now, I hope this works for everyone :)



Submit Comment

Comments

  1. Majid on June 22, 2010
    I am developing an application using AJAX and CSS. I have a webpage in which i have some hyperlinks. I want that when ever some one move the cursor on some link, than mini preview should be loaded before clicking. I have done that but problem is that i want just the ist paragraph of the target webpage not the whole page. I dont want images in my preview window.
    Pls help

  2. SM on August 31, 2009

    You sure have a good knack for writing tutorials. Can you please write a similar small tutorial on parsing web pages with biterscripting ( http://www.biterscripting.com ) ? Thanks.

  3. Matt on August 11, 2009
    Sorry I haven't been able to reply lately. This could be a long conversation so if you still need help use the contact page and I will try to help you easier :)

  4. Mr M on August 05, 2009
    I tried, but still the result is not occuring :(, dont knw whts the problem, anyways, i am also trying to develop a program that when some one select data from one combo than data according to ist combo selection will show in 2nd combo box.

  5. Matt on August 04, 2009
    You won't, you retrieve the information the same way as above, when you get the information from the database you simply add them to a string like so:

    $query = mysql_query("YOUR QUERY HERE");
    while($getInfo = mysql_fetch_array($query)){
    $output .= '<option value=" ' . $getInfo["VALUE"] . ' ">' . $getInfo["ANOTHER VALUE"] . '</option>';
    }

    echo $output;

    and that will return information like this:

    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>

    Just apply this to what you are doing and use the javascript to return it within the <select></select> box with the:

    document.getElementById('YOUR SELECT ID').innerHTML

    Hope this makes it clearer

  6. Mr M on August 04, 2009
    Matt, i have tried just as u did ur previous GREAT program, but i m not getting the answer, one thing i know that i have to use loop to put the items in the combo, i m using that but not getting the answer, pls u try on this..

    Thanx

  7. Matt on August 04, 2009
    Not 100% sure, but with AJAX all you have to do is edit your php file and get it to output <option> tags and insert data from your mysql table. Just basically do what we have done above, but where it says:
    document.getElementById('searchResults').innerHTML

    you just need to change 'searchResults' with whatever your combo box id is and edit the php to output a different response. You will also need to call the javascript from a button using onclick and from a combobox on onchange :)

  8. Mr M on August 04, 2009
    Great Matt,
    I have got now, thank u so much for helping.
    Ok now i have another problem, that i want to make a program using AJAx and php. That is i have tow buttons and one combo, what i need is that when some one click on the first button so data from mysql table first column should be load in the combo and when some one click on the second button data from mysql table 2nd column should be load in the combo.
    Hope u get what i m saying, pls help in this regard.
    Thanks

  9. Matt on August 03, 2009
    Sure, i'll try:
    (\'' . $displayName . '\')">

    in the first part of this string you see (\' the backslash escapes this as a php quotation and recognises it as part of the string and will print it as (' the next part is :

    ' . this escapes the php string and prepares to print the next variable so (\'' . Is actually parsed in html as ('

    the last part is . '\') this is just the same as above but backwards the first apostrophe escapes the php statement and the \' is parsed as an actual quote. Hope this helps you understand slightly better!

  10. Mr M on August 03, 2009
    Hello again Matt, I m getting all what u have done in your tutorial, but i m getting problem only in the (\'' . $displayName . '\')">'. I mean, i m confusing in the double coutes and single coutes, can u make it a little easy :)

  11. Matt on July 28, 2009
    Oops seems to be a bug in my comments, ill sort that out in a min. As for your query, the sendToSearch is a custom function which will send the list item the user selects so for example if the list item is 'dogs' and they click it, the word 'dogs' will appear in the input text box. The bit you seem to be asking about is the brackets following the call to the function, this is literally how we send the string to the function the (\' is opening the quotation string but as we are writing this within a php echo we need to escape the single quote to let php know to parse this as a quotation not as a break in the php code.

    The '.$displayName.' is how we echo the php variable as text so using the example above, this will be parsed as sendToSearch('dogs'). Sorry if this didnt help, it's difficult to explain. If you need more help just post another comment :)

  12. Mr M on July 28, 2009
    Hello, nice tutorial, but i m finding problem in onClick="sendToSearch(\'' . $displayName . '\')">' . $displayName .'</li>'; part, pls explain this in detail specially this one ......... (\''.$displayName.'\')"