Personal blog for expressing my experiences

Auto Complete a textbox using AJAX, PHP and MySQL

This example illustrates how to create a auto completion text box using AJAX, PHP and MySQL. Data is being retrieved from MySQL database and displayed using AJAX. As of now only mouse movements are being handled but keyboard events are not handled.

The example carries explanation of some parts of the code, while one can download the source,study and reuse as per your convenience. You can download the source from here.

1. index.html

<script language=”JavaScript” type=”text/javascript” src=”suggest.js”></script>
<input type=”text” id=”PoNumber” alt=”Search Criteria” onkeyup=”searchSuggest();” autocomplete=”off”/>
<div id=”layer1″></div>

The page loads the `suggest.js` file wherein the `searchSuggest` function is described. The keyboard event handler in this occasion is the `onkeyup` which checks for each letter that is being entered in the textbox. A div element is also created so that the data that has been passed by JavaScript can be handled.

2. suggest.js

var searchReq = getXmlHttpRequestObject();

This above line creates a httpRequest object for passing values.

function searchSuggest() {
if (searchReq.readyState == 4 || searchReq.readyState == 0) {
var str = escape(document.getElementById(‘PoNumber’).value);
searchReq.open(“GET”, ‘searchSuggest.php?search=’ + str, true);
searchReq.onreadystatechange = handleSearchSuggest;
searchReq.send(null);
}
}

`str` gets the value from the textbox. Each word entered in the text box is being passed to this variable which forms a part of the function. Later the values are passed on to the `searchSuggest.php` file which does all the processing.

var curLeft=0;
if (str1.offsetParent){
while (str1.offsetParent){
curLeft += str1.offsetLeft;
str1 = str1.offsetParent;
}
}

`curLeft` defines the current left position which is being initialize to 0 as the begining. `offsetparent` returns a reference to the object which is the closest (nearest in the containment hierarchy) positioned containing element. `offsetParent` returns null when the element has style.display set to “none”. Since the element can be inside many hierarchies we loop along with each of them to get hold of the value.

ss.setAttribute(‘style’,’position:absolute;top:’+curTop+’;left:’+curLeft+’;width:150;z-index:1;padding:5px;border: 1px solid #000000; overflow:auto; height:105; background-color:#F5F5FF;’);

Here `ss` represents document id of the layer. In the above line the `style` property of the div tag is being set. The `position` should always be `absolute` else the layer will not be formed. The lower elements will be pushed down to accommodate the values that are being retrieved from the database. The `top`, `left` etc. are also being put to show to drop down (div layer). `overflow` is also set so for the scrolling effect in the div tag when it crosses the defined `height`.

The other stuff in the file should be self explanatory as it declares the variables and the functions.

3. database.php

function db_connect($server = ‘localhost’, $username = ‘root’, $password = ‘enigma’, $database = ‘suggest’, $link = ‘db_link’)

Please change the `server`, `username`, `password` and `database` name corresponding to yours.

4. searchSuggest.php
A self-explanatory file. This retrieves the data from the database and passes the output to the searchSuggest function in suggest.js.

23 Comments

  1. Nice script, its working well, thanks

  2. Chinju

    Hi,
    Thanks for this code.I tried your code and found that it’s working in firefox..In IE its not working as properly..How can i change that??Please help me..

    Thanks..
    Chinju

  3. Donn Walang katulad

    Thank you!!!

  4. Comment by post author

    I have used Firefox while developing the application. I am not in a position to test it in IE. My apologies.

  5. karthik

    Thank you

  6. spr

    i have two fields serialno , cityname. I\’ll be searching by cityname and when i\’ll click on any of the suggestion serialno of that particular cityname must be inserted in
    second textbox.
    How to do this?
    And if possible can anyone explain by an example
    thanks in advance

  7. Thimael

    Hi.

    I used this code in an oscommerce site, but when redirected to the advanced search, the script stop working.

    For example in http://passecomposse.com/oscommerce/advanced_search_result.php?keywords=as the script is not working, but if you do a manual advanced search, like in http://www.passecomposse.com/oscommerce/advanced_search_result.php?x=65&y=15&keywords=as&categories_id=&inc_subcat=1&manufacturers_id=&pfrom=&pto=&dfrom=&dto= the script works fine!

    How can it be?

    Best regards,

  8. hari vaag

    hello,

    does your code work in frames as i have 2 frames. one has the option of autocomplete and accordingly i have to show results in the next frame

    rgds
    hari vaag

  9. Comment by post author

    I have not tested this in iframes, but it should work.

  10. Nick Lachey

    Awesome post. Hereโ€™s a tool that lets your build your online database without programming. There is no need to hand code PHP. Cut your development time by 90%
    http://www.caspio.com/

  11. Mr C

    Nice, but just doesn\’t quite work in IE, shame as it\’s the best (easiest to use) that I\’ve found so far.

  12. Mr jackass

    Best I love it

  13. Jitsu

    Just thank you ๐Ÿ™‚

  14. x

    Nice ๐Ÿ™‚

  15. raj

    the search panel does remain still if after i types something and instantly delete the the word i typed.. can u solve that/???

  16. Tunde

    Just used it today in an application I am working on…very nice of you to share.

  17. pintoo

    thanks for this its really simplwe and ease to implement

  18. Rajesh

    Wonderful, I did not expect that the given code is accurately work… Thank u once again…

  19. My developer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using Movable-type on
    various websites for about a year and am worried about switching to another platform.
    I have heard great things about blogengine.
    net. Is there a way I can import all my wordpress content into
    it? Any kind of help would be greatly appreciated!

  20. bals

    Really Superb… Thanks a lot……

  21. deepanjan dey

    thanks

  22. gym

    Great blog.Really thank you! Cool.

Leave a Reply

23  −  19  =