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. reverse cell phone number lookup…

    Just what I was searching for, thanks for posting ….

  2. Dancers says:

    Its hard to find good help…

    I am forever proclaiming that its difficult to find quality help, but here is…

  3. reverse look up cell phone…

    I like this web blog very much so much great info ….

  4. Great website…

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

  5. Related……

    [...]just beneath, are numerous totally not related sites to ours, however, they are surely worth going over[...]……

  6. More info…

    [..] More info here [..]…

  7. Great Websites…

    [...]here are some links to websites that we link to because we think they are worth taking a look at[...]……

  8. Visitor recommendations…

    [...]one of our visitors recently recommended the following website[...]……

  9. Blogs ou should be reading…

    [...]Here is a Great Blog You Might Find Interesting that we Encourage You[...]……

  10. Check this out…

    [...] that is the end of this article. Here you’ll find some sites that we think you’ll appreciate, just click the links over[...]……

  11. Read was interesting, stay in touch……

    [...]please visit the sites we follow, including this one, as it represents our picks from the web[...]……

  12. Great website…

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

  13. Links…

    [...]Sites of interest we have a link to[...]……

  14. Abstract Art says:

    Cool sites…

    [...]we came across a cool site that you might enjoy. Take a look if you want[...]……

  15. Thank you…

    I was very pleased to find this web-site.I wanted to thanks for your time for this wonderful read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you blog post….

  16. stock market says:

    Websites we think you should visit…

    [...]although websites we backlink to below are considerably not related to ours, we feel they are actually worth a go through, so have a look[...]……

  17. Great information…

    This is certainly impressive. Among stare upon this realisation ingredients therefore we are taken aback. We are most certainly fascinated by this kind of tips. Folk appreciate your quotation, and benefits the effort while in this. Please keep adding i…

  18. Sources…

    [...]check below, are some totally unrelated websites to ours, however, they are most trustworthy sources that we use[...]……

  19. Websites worth visiting…

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

  20. Gems form the internet…

    [...]very few websites that happen to be detailed below, from our point of view are undoubtedly well worth checking out[...]……

  21. Blogs ou should be reading…

    [...]Here is a Great Blog You Might Find Interesting that we Encourage You[...]……

  22. Great…

    [...]here are some hyperlinks to internet sites that we link to since we believe they may be really worth visiting[...]…

  23. You should check this out…

    [...] Wonderful story, reckoned we could combine a few unrelated data, nevertheless really worth taking a look, whoa did one learn about Mid East has got more problerms as well [...]……

  24. Awesome website…

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

  25. sex kontakte says:

    Thumbs up…

    I saw this really good post today….

  26. TusMedios says:

    Websites you should visit…

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

  27. Great website…

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

  28. Informative and precise…

    Its difficult to find informative and accurate info but here I noted…

  29. reverse cell phone lookup…

    I like this blog its a master peace ! Glad I observed this on google ….

  30. Check this out…

    [...] that is the end of this article. Here you’ll find some sites that we think you’ll appreciate, just click the links over[...]……

  31. Drinking says:

    mite…

    [...]This problem does not need medications or doctor’s consultation. It can be cure d with home remedies[...]…

  32. ………..

    My spouse and i suppose in the meantime i’ll settle for book-marking as well as adding the Feed to my own Google consideration. My partner and i look forward to brand new revisions and may share this site with my personal Facebook class….

  33. Monster says:

    mend…

    [...]Apart from that, another popular heartburn home remedy is to drink plenty of water after you have had your meal so that it helps the digestion[...]…

  34. Awesome webpage…

    [...] Now each time an individual looks at the existing fashion assertion, it is normally measurement zero [...]…

  35. Why don’t others write as good as you?…

    [...]If only all the websites at the top ten could possibly write such as you here. You ought to get a lot of merits due to this. Thumbs[...]……

  36. Websites you should visit…

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

  37. Related.. Trackback…

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

  38. darmowy seks…

    Glebokie cipy do podgladania bezlatnie….

  39. Extra Reading…

    [...]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[...]…

  40. Online Article……

    [...]The information mentioned in the article are some of the best available [...]……

  41. harga helm says:

    Cool sites…

    [...]we came across a cool site that you might enjoy. Take a look if you want[...]……

  42. Sites we Like……

    [...] Every once in a while we choose blogs that we read. Listed below are the latest sites that we choose [...]……

  43. Male Extra says:

    Sites we Like……

    [...] Every once in a while we choose blogs that we read. Listed below are the latest sites that we choose [...]……

  44. … [Trackback]…

    How do you do? our family loves your nice editorial thanks and pls keep it on…

  45. Cool sites…

    [...]we came across a cool site that you might enjoy. Take a look if you want[...]……

  46. important links…

    Guys check out these important links…

  47. Websites worth visiting…

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

  48. Related……

    [...]just beneath, are numerous totally not related sites to ours, however, they are surely worth going over[...]……

  49. Tumblr article…

    I saw a writer writing about this on Tumblr and it linked to…

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