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.

26 Comments »

  1. jake Said,

    September 28, 2011 @ 3:22 pm

    Nice script, its working well, thanks

  2. Chinju Said,

    October 5, 2011 @ 11:18 am

    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 Said,

    October 8, 2011 @ 5:21 pm

    Thank you!!!

  4. Ophiophagus Said,

    October 11, 2011 @ 8:25 pm

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

  5. karthik Said,

    December 1, 2011 @ 5:39 pm

    Thank you

  6. spr Said,

    December 30, 2011 @ 10:50 am

    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 Said,

    January 2, 2012 @ 9:42 pm

    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 Said,

    January 27, 2012 @ 2:42 pm

    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. Ophiophagus Said,

    January 27, 2012 @ 9:23 pm

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

  10. Nick Lachey Said,

    February 12, 2012 @ 1:20 am

    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 Said,

    March 6, 2012 @ 10:50 pm

    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 Said,

    March 17, 2012 @ 12:34 pm

    Best I love it

  13. nick Newman Said,

    April 6, 2012 @ 6:46 pm

    thank you

  14. Jitsu Said,

    April 15, 2012 @ 12:22 pm

    Just thank you :)

  15. x Said,

    April 23, 2012 @ 3:47 pm

    Nice :)

  16. raj Said,

    June 5, 2012 @ 9:43 pm

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

  17. Tunde Said,

    June 6, 2012 @ 2:39 pm

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

  18. pintoo Said,

    June 22, 2012 @ 3:18 pm

    thanks for this its really simplwe and ease to implement

  19. Rajesh Said,

    July 22, 2012 @ 8:13 pm

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

  20. captcha breaker Said,

    September 11, 2012 @ 4:24 am

    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!

  21. bals Said,

    October 11, 2012 @ 6:26 pm

    Really Superb… Thanks a lot……

  22. deepanjan dey Said,

    April 1, 2013 @ 11:28 pm

    thanks

  23. manjari agarwal Said,

    January 7, 2014 @ 6:51 pm

    thanx a lot,
    i will try too many jquery autocomplete textbox all do good but whenever i add datetimepicker on same page autocomplete functionality stops.
    but from ur script both the autocomplete textbox and datetimepicker works correct on same page!!
    it superb and save lot of time!!!

  24. ravikant Said,

    January 24, 2014 @ 11:06 am

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

  25. ravikant Said,

    January 24, 2014 @ 11:07 am

    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

  26. sundar Said,

    February 20, 2014 @ 1:07 pm

    Great coding. nice explanation. thanx a lot,
    i will try too many jquery autocomplete textbox all do good but whenever i add datetimepicker on same page autocomplete functionality stops.
    Thanks for sharing this information.

    http://www.dreamdestinations.in/

RSS feed for comments on this post · TrackBack URI

Leave a Comment