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.

5,339 Responses to “Basic Auto Suggest with Ajax and PHP”

  1. [...]below you’ll find the link to some sites that we think you should visit[...]…

    [...]here are some links to sites that we link to because we think they are worth visiting[...]…

  2. Travel Offers…

    [...]all of these web sites may well not really be absolutely relevant towards our website however we most definitely believe you should see them[...]…

  3. Taylor Armstrong Says It’s An Incredible Posting Well Done…

    [...] Excellent post, thought we would put several not related info, nevertheless still worth taking a look fyi have one heard the news concerning Mid East now has a lot more worries as well . [...]…

  4. Benefits of LED Bulbs…

    [...]beneath you’ll get the hyperlink to some web-sites that we believe you should pay a visit to[...] …

  5. quick weight loss diets reviews…

    [...]below are some great sites that are interesting and definitely worth visiting [...]……

  6. air purifier…

    [...]When i first started to provide HEPA air cleaners to the customers the big concern was for normal house hold allergies that came from dust, pollen, pet dander and smoke[...]…

  7. Tinnitus Miracle Information Database…

    [...]we love to honor other websites on the internet, even if they aren’t really related to our post, by linking to them.[...]…

  8. Buy Electric Guitar Packages at Half Off…

    [...]the time to read or visit the content or sites we have linked to below the[...]…

  9. [...]while the sites we link to below are completely unrelated to ours, we think they are worth a read, so have a look[...]…

    [...]just below, are some totally unrelated sites to ours, however, they are definitely worth checking out[...]…

  10. Background Check…

    [...]while the sites we link to below are completely unrelated to ours, we think they are worth a read, so have a look[...]…

  11. Rob Rasner says:

    Rob Rasner Suggests Its A Fantastic Post Congratulations…

    [...] Here might be various other advice everyone may well become interested around, dont stop… [...]…

  12. Paul says:

    Site…

    [...]the time to read or visit the content or sites we have linked to below the[...]…

  13. Flax Seeds Benefit…

    [...] below you’ll find the link to some sites that we think you should visit. Posted in [...]…

  14. You Might Like This Site…

    [...]below you’ll find the link to some sites that we think you should visit[...]…

  15. 1.) Locksmithing…

    2.) [...]when we find a site that we think is cool we like to link to it and here is one of those sites. Check it out[......]…

  16. Colon Cleanse Reviews…

    [...]below you’ll find the link to some sites that we think you should visit[...]…

  17. Games For Girls…

    [...]here are some links to sites that we link to because we think they are worth visiting[...]…

  18. Effective Weight Loss Programs…

    [...]just below, are many pretty much unrelated sites from this one, but they are absolutely worth reading[...]…

  19. Russell Armstrong Suggests It’s An Incredible Story Congratulations…

    Excellent info; reckoned I would track-back to it. btw did you read the news on the tsunami has now got a lot more worries also :(

  20. Buy Yankee Candles at Half Off…

    [...]the time to read or visit the content or sites we have linked to below the[...]…

  21. Use CieAura says:

    Cieaura Says It’s An Incredible Article Cool!…

    [...] Best post reckoned I might add some unrelated data, yet still worthwhile checking them out… [...]…

  22. הכרויות בטלפון…

    [...]below you’ll find the link to some sites that we think you should visit[...]…

  23. 1.) Security…

    2.) [...]below you’ll find the link to some sites that we think you should visit[...]…

  24. Cheap trips to hawaii…

    [...]while the sites we link to below are completely unrelated to ours, we think they are worth a read, so have a look[...]…

  25. Anti Wrinkle Cream Reviews By Real People…

    [...]we like to honor other sites on the web, even if they aren’t related to us, by linking to them. Below are some sites worth checking out[...]…

  26. Mesothelioma says:

    Mesothelioma Sites…

    [...]below you’ll find the link to some sites that we think you should visit[...]…

  27. Weekly RoundUp…

    Take a gander at some of the blogs that we have been spotting throughout the week….

  28. Smoked Salmon Gifts…

    [...]here are some links to sites that we link to because we think they are worth visiting[...]…

  29. how to build muscle quickly…

    [...]here are some links to sites that we link to because we think they are worth visiting[...]…

  30. Indie Films Says Its An Incredible Post Keep It Up…

    Cool news, thinking I might add several not related posts, nevertheless still worth checking them out!!!…

  31. Meat Slicers says:

    Your Friend & Partner…

    I really think your blog is great! I’ve added a link back here; I hope that’s alright as I’d like my readers to check your site & articles out. It’s Here on my site’s blog. Always like to honor high quality content. Great job!…

  32. margarita machines…

    [...]we like to honor other sites on the web, even if they aren’t related to us, by linking to them. Below are some sites worth checking out[...]…

  33. 6 week body makeover reviews…

    [...]the time to read or visit the content or sites we have linked to below the[...]…

  34. sold gold says:

    Rising gold Prices…

    [...]while the websites we link to below are somehow unrelated to ours, we think they are worth a read, so have a look[...]…

  35. Sensa Scam says:

    Sensa Information…

    [...]here are some links to sites that we link to because we think they are worth visiting[...]…

  36. diapers says:

    free bets…

    [...]just below, are some totally unrelated sites to ours, however, they are definitely worth checking out[...]…

  37. air purifier…

    [...]I first started to provide HEPA air cleaners to the customers the large concern was for normal house hold allergies that originated from dust, pollen, pet dander and smoke[...]…

  38. diaper bags…

    [...]the time to read or visit the content or sites we have linked to below the[...]…

  39. Does Healthy Trim Work…

    [...]just below, are some totally unrelated sites to ours, however, they are definitely worth checking out[...]…

  40. SEOXP SEO Service…

    [...]below you’ll find the link to some sites that we think you should visit[...]…

  41. portable air conditioning units prices…

    [...]just below, are some totally unrelated sites to ours, however, they are definitely worth checking out[...]…

  42. [...]while the sites we link to below are completely unrelated to ours, we think they are worth a read, so have a look[...]…

    [...]just below, are some totally unrelated sites to ours, however, they are definitely worth checking out[...]…

  43. hostgator free…

    [...] just down below, are a few totally unrelated sites to ours, yet, they’re certainly well worth checking out [...]…

  44. Download Full Movies…

    [...]below you’ll find the link to some sites that we think you should visit[...]…

  45. Web Builder…

    [...]Loving the blog and checking other links[...]…

  46. how to get ripped…

    [...]we like to honor other sites on the web, even if they aren’t related to us, by linking to them. Below are some sites worth checking out[...]…

  47. Web Site Builders It’s An Incredible Posting Congratulations…

    [...] Fantastic info; reckoned I would track-back on it, btw have one learn concerning the earthquake has now got a lot more issues too :-) [...]…

  48. vigrx plus says:

    [...]we like to honor other sites on the web, even if they aren’t related to us, by linking to them. Below are some sites worth checking out[...]…

    [...]the time to read or visit the content or sites we have linked to below the[...]…

  49. Amazing website…

    [...]while the sites we link to below are completely unrelated to ours, we think they are worth a read, so have a look[...]…

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