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. ramya on February 16, 2014
    shows an error in $s = $_REQUEST["s"];

  2. ramya on February 16, 2014
    shows an error in $s = $_REQUEST["s"];

  3. rocky on February 03, 2014
    <form id="quick-search" action="../search" method="post" >

    u should try it...

    <form id="quick-search" action="search.php" method="post" >
    and create file search.php
    then get value of input box using $_POST.

  4. Surya Teja on January 24, 2014
    <form id="quick-search" action="../search" method="post" >
    As i execute the code its not redirecting to js and php file.......problem might be with action="../search"..........what i should write here to redirect..................pls help me....................surya.king1008@gmail.com

  5. Electrolysis on October 13, 2013
    It seems a great tutorial but for some reason when I try to use it, nothing appears. I opened the php file and it said "Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /home/.../livesearch.php on line 15"

    Any ideas?

  6. binaryjc on October 02, 2013
    thaank youu!

  7. hers on July 19, 2013
    ese

  8. Tucker on June 18, 2013
    mysql is depreciated. You should update this tutorial to either PDO or mysqli.

  9. Kevaughn on June 04, 2013
    This is exactly what I am looking for. Havent tested it yet, will try it now

  10. Leslie on May 22, 2013
    This was just what I was looking for! Thank you so much for your time and clear explanations!

  11. lol on May 08, 2013
    cant find search file..try to run the code in your machine,there's some error.

  12. lol on May 08, 2013
    cant find search file..try to run the code in your machine,there's some error.

  13. eby on April 18, 2013
    am not soo conversant with ajax so am finding it difficult to know where to put my codes can I have help in that

  14. szfd on April 12, 2013
    dfdzdff

  15. fsd on April 12, 2013
    fgfgsf

  16. kumama on April 04, 2013
    Thank You.

  17. reyaz ahmad on February 12, 2013
    Thank You

  18. shah on January 30, 2013
    worked superb. :) was like as if i was in a classroom with a tutor in front of me.

    all i did was copied the js file content and pasted in script tag of the html file and changed the action of the form. and a few entries in the DB. perfect :) thanks a lot :)

  19. sikkandar bhooto on January 22, 2013
    Very Nice. its working great!!!!!!!!!!

  20. w on January 03, 2013
    ww

  21. kimchit on December 20, 2012
    how to get it

  22. kacper on December 07, 2012
    Unfortunatelly, did'nt working to me. Should I put in .html header includes of any ajax files, or/and livesearch.js file? :(

  23. 33 on October 27, 2012
    ee

  24. agnes on October 18, 2012
    thanks a lot

  25. ranjan on September 12, 2012
    afdga

  26. Reshma jain on September 12, 2012
    nice quote. too helpfull......

  27. burhanali on September 04, 2012
    in the case of multiple fields what should i do

  28. Cool guy on August 01, 2012
    Great! Thanks!

  29. samuel on July 21, 2012
    OK good but actual problem is when the result is displaying the below part is moving down and also i need to dispaly data two textboxs one after one my mail id is sam.saidu3@gmail.com

  30. Lou on June 27, 2012
    How would you edit this script to allow for multiple element ID to work? Need to have a live search for medications and want to be able to add at least 8 meds. This works great for the first ID, but can't get to work for the rest.

    Thanks

  31. nena on April 27, 2012
    thanks alot
    this is working

  32. ROCKESH RONITH on March 29, 2012
    is working???

  33. Mahamed on January 02, 2012
    Sorry, it was my mistake the code perfectly. Thank you

  34. Mahamed on January 02, 2012
    Codes seem to be OK but for me it didn't work. Though on form action i put livesearch.php but the script doesn't refference the livesearch.js which i also i have included on header side of livesearch.html. I am php programmer, i am not good at all on javascript so i think there might problem on javascript but php code is fine.

  35. Matt on May 07, 2011
    Thanks KN, no worries :)

  36. KN on May 07, 2011
    This is a very well explained and coded tutorial, thoroughly thought out, i cannot thank you enough!!

    10/10

  37. Matt on November 16, 2010
    Thanks Patrick. There is a very easy way to limit the database results, simply add 'LIMIT 5' onto the end of the query like this:

    $query = "SELECT * FROM news WHERE newsContent LIKE '%" . $s . "%' LIMIT 5";

  38. Patrick Hurley on November 16, 2010
    Actually, is there a way to edit the php script so that a maximum number of results are displayed at a time? I need to limit the results to 5 items as I'm working with a large database and the printed results are rather large!

    Many thanks.

  39. Patrick Hurley on November 16, 2010
    Thank you so much.

  40. 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

  41. 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.

  42. 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 :)

  43. 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.

  44. 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

  45. 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

  46. 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 :)

  47. 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

  48. 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!

  49. 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 :)

  50. 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 :)

  51. 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.'\')"