Script Perfect

         Random snips of code and bugs

Basic Auto Suggest with Ajax and PHP

Posted by Tim On September - 11 - 2009

ajax auto suggestYou see it in Yahoo, Google, Bing, and all over the web. As you type into a search feild a box appears before your eyes showing you suggestions based on what you are typing. This offers more than just ease of use for your visitors, it allows them to see other content related to their search that they may have been otherwise unaware of. There are many tutorials on this subject, many of which rely heavily on API’s or copyright protected files.

Developing an auto suggest form is rather simple, with the right methods you too can churn out a professional looking auto suggest form without the complicated mess that many others provide.  Visitors are likely to return to your site (provided the content is valid) to use features like this because so many other sites are slow in developing this type of technology.

The concept is simple, we run a JavaScript function every time a user presses a key in a search box, we use Ajax to send and receive data to a php search function and return the results to our page.

Creating the Form

All we need for this example is a text input, you will need to add a submit or other control if you desire it. We will also need to create a DIV which will display our results. The text input will use the onkeypress event to trap the users input and pass it through to our functions.
Input Area Setup + CSS

<!–    .searchcontainer {              border: 0px;            width: 320px;   }       .searchresults {                border: 1px solid #000;                 background: #D4D4FF;    } –>
<div class="searchcontainer">
<div class="searchbar"><input id="search" onkeypress="javascript:search();" type="text" /></div>
</div>

Our text input calls the functions “search” which will take the input from the field and use some Ajax to return the results into our DIV “searchresults”. As with Ajax we need to set up our XMLHttpRequest which acts as the communicator between our webpage and whatever we link to it.

Ajax XMLHttpRequest

<script type="text/javascript">// <![CDATA[
        function createXMLHttpRequest() {
        if (typeof XMLHttpRequest != 'undefined') {
                return new XMLHttpRequest();
        }
        try {
                return new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
                try {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
        }
        return false;
}
// ]]></script>

Setting up the Search Function

So now that the form is created and we have our XML function set up for our Ajax request we can create our search function in JavaScript which will post the data from the form to our search php script.

JavaScript Search Function

<script type="text/javascript">// <![CDATA[
function search(){
        var userInput = 'search='+document.getElementById('search').value;
        var xmlReq = createXMLHttpRequest();
        xmlReq.open("POST","search.php", true);
        xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xmlReq.onreadystatechange = function() {
                if(xmlReq.readyState == 4 &#038;&#038; xmlReq.status == 200) { 
                        document.getElementById('searchresults').innerHTML = xmlReq.responseText;
                        document.getElementById('searchresults').style.display = "block";
                }
        }
        xmlReq.send(userInput);
}
// ]]></script>

The code above creates a new XMLHttpRequest object and sends the input from the text box to our search php file by posting the data. Once the function receives a response from the search php file it will display the results within the DIV searchresults on our page.

Let’s write a basic search php file, we will use the LIKE statement in our sql statement.

Creating search.php

$host = "localhost";
$user = "username";
$pass = "password";
$database = "my_database";
$c = mysql_connect($host, $user, $pass) or die(mysql_error());
mysql_select_db($database, $c);
$search = $_POST[’search’];
$result = mysql_query("Select * from images where NAME like ‘$search%’ LIMIT 5");
while($i = mysql_fetch_assoc($result)){
extract($i);
echo "<strong>Name: </strong>$NAME

<hr />";
}
mysql_close($c);
?&gt;

The php code above runs a query on a table called “images”, you will need to change this to match whatever table you want to run the query on. We also use a LIMIT of 5 because we do not want to load the users page with every result, especially if it is a large database. Once we get our result we simply echo them out and our “search()” function receives the result to update our page.

Currently there will be no interaction on the results that we echo out, you could easily modify them to include a link to the page where the result would be relevant.

Taking it Further

To make your auto suggest forms look and feel more professional it would be a good idea to add some nice styling to your results, you can even include images. Changing the DIV styles around so that if floats on top of the page will make it so that the results do not push content on your main page out of the way.

Error handling and requiring a minimum number of characters before the search function is run is also a good idea. There are many avenues you can take to improve this form and function, if you develop it further and want to show off what you have done with it then leave us a comment below.

2 Responses to “Basic Auto Suggest with Ajax and PHP”

  1. tom says:

    This Code does not work. What are you intending to show with this ?
    Don’t you test the codes before publishing them ?

  2. Sandy says:

    It doesn’t work………..

Leave a Reply

Spam protection by WP Captcha-Free

About Me

I am an independent web developer and webmaster of many sites. The main goal of Script Perfect is to provide answers to some of the hard to find questions when it comes to website design and coding.

Twitter