Using jQuery UI’s Autocomplete to Populate a Form

It’s been a year and a half since I last posted about jQuery autocomplete. It’s come a long long way since then. In fact it’s really incredible now. The jQuery UI team has provided event hooks throughout the entire process while still providing a really robust experience if you just use it out of the box. For my case, I wanted to pre-populate more than just the current field with data. Using the “select” event, I was able to provide a custom handler that used the auto-suggest data to update other fields. This is very simple to implement and yields a really nice bump in the usability.

The use case is simple. A user starts to enter a city name, “san”. We use the text fragment and make a request for city / state / zip matches from the database or other source. We then present those to the user as an autocomplete option. If they select one, we update the city, state and zip fields with the selected data.

To implement this, you’ll want to generate an ajax handler that can generate JSON data. You can use a local array as your data source, however, the real power of auto-suggest is bringing the full weight of your database to bear. In many projects the data is too large to load into a static array. Since I use PHP mostly in my daily work, that’s what the example here is in. However, this could be done in any language. The two required fields, when using an object are “label” and “value”. The label is the text that will be shown to the user and “value” is the data that will be set in the current field. I generate an array of result data on the fly and then use PHP’s built in json_encode() function to bundle it up and return it to the user. This truncated example, shows the data being returned from my handler. Notice that I’m also passing back “city”, “state” and “zip” in addition to the “label” and “value” fields.

View Code JAVASCRIPT
[{"city":"San Diego","state":"CA","zip":"92101","value":"San Diego","label":"San Diego, CA 92101"}]

With the additional data in the response, I can assign these structured values to other fields in the form. This solved the main gripe I had with the autocomplete feature before, simple handling of JSON. While it was feasible under the old model, it required far more effort and development. This is all built into the core jQuery UI library. As you can see in the example below, it is insanely simple to write robust forms that can auto-populate based off the data in a single field.

This of course just scratches the surface of what you can really do with the autocomplete feature though. The jQuery UI team has done a great job of providing hooks to all the events, which really allows you to go nuts with the functionality. For example, using a function instead of an ajax file or local variable, you could serialize the entire form and send it via ajax. Then as your callback, pass the data to generate the suggestions to the user. Take a few minutes and read over the entire documentation, it’s really very powerful. You also have a wide variety of visual themes available, including the option to build your own. I’m using the default theme generated by the jQuery themeroller tool here.

Working Demo

Try entering, “sa”, “ch” or “ph” into the City field to see it in action. In this case, I look for a string match in the city name, but you could just as easily include the state, zip and so on.

The Code

You can see in the javascript below, I’m providing a handler for the “select” event that updates the other fields. I find that sometimes the event doesn’t properly update the fields essentially leaving the source field, city, with whatever text fragment I’ve entered. This seems to happen more often on mouse events but I haven’t spent much time tracking the cause down. If you happen to see what the issue is, please leave it in the comments!

<link rel="stylesheet" href="http://static.jquery.com/ui/css/base2.css" type="text/css" media="all" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
 
$(document).ready(function(){
	var ac_config = {
		source: "/ajax/demo_cities.php",
		select: function(event, ui){
			$("#city").val(ui.item.city);
			$("#state").val(ui.item.state);
			$("#zip").val(ui.item.zip);
		},
		minLength:1
	};
	$("#city").autocomplete(ac_config);
});
</script>
<form action="#" method="post">
	 <p><label for="city">City</label><br />
		 <input type="text" name="city" id="city" value="" /></p>
	 <p><label for="state">State</label><br />
		 <input type="text" name="state" id="state" value="" /></p>
	 <p><label for="zip">Zip</label><br />
	 	 <input type="text" name="zip" id="zip" value="" /></p>
</form>

An over simplified callback script that does a simple text match on the data entered into the field.

<?php
 
// Data could be pulled from a DB or other source
$cities = array(
	array('city'=>'New York', state=>'NY', zip=>'10001'),
	array('city'=>'Los Angeles', state=>'CA', zip=>'90001'),
	array('city'=>'Chicago', state=>'IL', zip=>'60601'),
	array('city'=>'Houston', state=>'TX', zip=>'77001'),
	array('city'=>'Phoenix', state=>'AZ', zip=>'85001'),
	array('city'=>'Philadelphia', state=>'PA', zip=>'19019'),
	array('city'=>'San Antonio', state=>'TX', zip=>'78201'),
	array('city'=>'Dallas', state=>'TX', zip=>'75201'),
	array('city'=>'San Diego', state=>'CA', zip=>'92101'),
	array('city'=>'San Jose', state=>'CA', zip=>'95101'),
	array('city'=>'Detroit', state=>'MI', zip=>'48201'),
	array('city'=>'San Francisco', state=>'CA', zip=>'94101'),
	array('city'=>'Jacksonville', state=>'FL', zip=>'32099'),
	array('city'=>'Indianapolis', state=>'IN', zip=>'46201'),
	array('city'=>'Austin', state=>'TX', zip=>'73301'),
	array('city'=>'Columbus', state=>'OH', zip=>'43085'),
	array('city'=>'Fort Worth', state=>'TX', zip=>'76101'),
	array('city'=>'Charlotte', state=>'NC', zip=>'28201'),
	array('city'=>'Memphis', state=>'TN', zip=>'37501'),
	array('city'=>'Baltimore', state=>'MD', zip=>'21201'),
);	
 
// Cleaning up the term
$term = trim(strip_tags($_GET['term']));
 
// Rudimentary search
$matches = array();
foreach($cities as $city){
	if(stripos($city['city'], $term) !== false){
		// Add the necessary "value" and "label" fields and append to result set
		$city['value'] = $city['city'];
		$city['label'] = "{$city['city']}, {$city['state']} {$city['zip']}";
		$matches[] = $city;
	}
}
 
// Truncate, encode and return the results
$matches = array_slice($matches, 0, 5);
print json_encode($matches);
This entry was posted in JavaScript, jQuery, UX Design and tagged , , , . Bookmark the permalink.

69 Responses to Using jQuery UI’s Autocomplete to Populate a Form

  1. st4n says:

    hi, i have read your example of autocomplete-populate.. i have worked on your source with mysql db. i populate a form with a row of the db.. i have a question for you.. In your opinion how can I do to populate two form with two different tables of db .. and relate to each other?

    example.. if i select newyork and populate the form in the other form i want the other values related newyork of the other table??

    excuse me for my bad english.. i wait your help.thanks.

  2. Tri says:

    I just got started messing with jQuery UI this week and I’m currently messing around with autocomplete. I’m confused on how to use the “select” event. This is my sample code: http://dpaste.com/200147/

    It’s an example straight from the jQuery UI documentation. I’m totally lost on what ui.item returns. I know ui.item is the selected item, but I don’t know its properties and methods. How can I find this out?

    For this example, I simply want to throw an alert of what has been selected by using ui.item. I tried to copy your example but it didn’t quite work.

    Thanks in advance.

    cheers,
    Tri

  3. Erik says:

    I use firebug in firefox and then you can use console.log(ui) to see the entire object.

  4. Erik says:

    @st4n The best approach for getting data out of your database is really beyond the scope of this post, but read up on MySQL joins.

  5. aphill70 says:

    Hey bro,

    Question for you I for some reason can get any field but the field i am searching on to propogate. so when i hit the enter button on my autocomplete selection. any ideas why this might be?

    $(document).ready(function(){
    	var ac_config = {
    		source: "/ajax/user.ajax.php",
    		select: function(event, ui){
    			$("input[name=firstname]").val(ui.item.firstname);
    			$("#lastname").val(ui.item.lastname);
    			$("#address1").val(ui.item.address1);
    			$("#address2").val(ui.item.city);
    			$("#address3").val(ui.item.state);
    			$("#email1").val(ui.item.email);
    			$('#phone').val(ui.item.phone);
    			},
    		minLength:1
    	};
    	$("#firstname").autocomplete(ac_config);
    });
                    
  6. Erik says:

    @aphill70 I noticed some inconsistent behaviors with mouse events, but haven’t seen any with keyboard events. Make sure that your selectors are correct, the firstname one you have here differs from the others, like phone. I suspect you’ve neglected to define the phone input with an id=”phone” attribute.

  7. Pavan says:

    Hello,

    Thank you for the post does any one know how to do full text search with out using ashx file in asp.net 3.5

  8. pierrot says:

    Hello, I was looking for exactely that code. Howerver, I can not make it working even if I copy pas the code.
    I thik is because of the php code. In that example, it miss the ‘ at state and zipe : state => ‘state’.

    Isn’t?

    Also what does the “$term = trim(strip_tags($_GET[‘term’]));”

    Where does come from the $_GET[‘term’]?
    Where is it initiate, I can ot see a trace of it into the form?

    Many thank for your explication because I really need a such code
    :o)

  9. Erik says:

    @pierrot The code could probably be clearer. The state and city are passed back (use Firebug to inspect your responses). The foreach loop sets a value to $city to which I add two additional values, for a total of 5 unique keys before I assign it to the matches array that is ultimately returned to the client.

    The trim() and strip() tags just do a little bit of data cleaning. If you are going to submit this in a database call, I would consider more robust validation of your values. Look at $mysqli->real_escape_string() documentation for a good example on how to do that. http://us2.php.net/manual/en/mysqli.real-escape-string.php

    The value in $_REQUEST[‘term’] is set by the UI plugin and it holds the value of the input field on the client so far.

  10. Greg says:

    Having trouble duplicating your example. Possible you provide me with a .zip file??

    Also…. I have a database with “ZipCode”, “City’, “State”… It is called from the following function and returns a fetch_array. Can you assist on how to implement the database?

    function getAllZipCityState() {

    // Get the longitude and latitude for the zip code.
    $query = ‘SELECT ‘ . $this->dbZip . ‘, ‘ . $this->dbCity . ‘, ‘ . $this->dbState . ‘ ‘;
    $query.= ‘FROM ‘ . $this->dbTable . ‘ ‘;

    //$qry = mysql_query($query,$this->db);
    $qry = $this->db->query($query);
    if(!$qry){
    echo “MySql Error #”.mysqli_errno($this->db).': ‘.mysqli_error($this->db).”;
    die;
    }
    return mysqli_fetch_array($qry);
    }

    Thanks!

  11. Greg says:

    Problems resolved. Now facing another error, Notice: Undefined index: city in C:\wamp\www\gregphp\inc.ZipCodes.php on line 84 from the following line… foreach($cities as $city){

    …Continued
    $citiesQry = $zip->getAllZipCityState();
    while ($row = $citiesQry->fetch_assoc()) {
    $cities[] = $row;
    }// Cleaning up the term
    $term = trim(strip_tags($_GET[‘term’]));

    // Rudimentary search
    $matches = array();
    foreach($cities as $city){
    if(stripos($city[‘city’], $term) !== false){
    // Add the necessary “value” and “label” fields and append to result set
    $city[‘value’] = $city[‘City’];
    $city[‘label’] = “{$city[‘City’]}, {$city[‘State’]} {$city[‘ZipCode’]}”;
    $matches[] = $city;
    }
    }

    // Truncate, encode and return the results
    $matches = array_slice($matches, 0, 5);
    print json_encode($matches);

    ?>

  12. Erik says:

    @greg Your error is a case issue. ‘City’ != ‘city’ you’ll need to update all instances to use the same case. The line after the one you see the error with references stripos($city[‘city’], $term) and I think that’s where your problem is. Good luck.

  13. noel says:

    Hello Sir,
    I’ve been trying to follow the instructions on your code but i just couldn’t make it if i try to fetch data from the database. Please guide us on how to fetch the data and use it to be able to use your example. i hope you’ll be able to give us information.

    1. fetch data
    2. how to apply fetch data in replacement of your sample arrays of data.

    if it wouldn’t be too much please send the complete files :)

    thanks

  14. flo says:

    Hello,

    I’m using ui autocomplete and it works fine with firefox but there is a problem with IE.

    IE don’t write the value of ID in the hidden input.

    js line : $("#MembreId").val(ui.item.id);

    html line :

    Is there another way to demand to IE to write the ID in the input with jquery.

    Thanks a lot.

  15. dang says:

    I just want to tell you how much I appreciate this example. It is simple and to the point which is exactly what I needed! Thank you!

  16. Live says:

    Hi, I’m trying to implement your code to populate an INVOICE, and getting its ITEMS from a Database is this possible?

    Also, how do I style the Suggestions? When I copy and paste them on the computer, I can’t find the CSS for your code.

    Thanks.

  17. Live says:

    Oh silly me, you download the CSS. I’m sorry for being such a newbie.

  18. Live says:

    Hi, thanks for this wonderful tutorial, it’s really great.

    I’m new to jquery, but I’ve some good experience with Php+MySQL, in your example on this blog, you populated the array manually with the cities information.

    Now, I want to replicate that, and what MySQL Query should I produce?

    Something like, “SELECT * FROM customers WHERE customer_name LIKE ‘%…

    Can you post a quick response on how to generate a MySQL Result Array for PHP to be used with your Autocomplete script.

    I’m really having trouble getting results from a MySQL Database.

    Thank you so much for your help. :)

  19. Live says:

    It’s so simple, I really need to study more.

    $items = array();
    $query = “SELECT * FROM items LIMIT 5 “;
    $result = mysql_query($query);
    while($row = mysql_fetch_assoc($result)){
    $items[] = $row;
    }

    More power to your blog sir! :)

  20. Pingback: Using jQuery Autocomplete with Lasso « IntrAktv

  21. Peter Bata says:

    I created both an html and a php file. I copied/pasted the code that you kindly provided. I run the html file, can see the three required form fields. When I begin entering New inthe city field for example, I am not presented with the choices available in the demo_cities.php file. Thank you.

  22. Robert says:

    This is fantastic, just what I’ve been looking for, but I need to integrate it to autopopulate a form on Drupal. Can anybody point to a link / tutorial on how to integrate this function into Drupal? I have a client who needs to be able to tap into a table which holds locations. I can probably figure it out but if there is anything out there which explains how to do it, I would appreciate a link.

    Thanks!

  23. Todd Young says:

    I stumbled upon jQuery last-night and it solved a problem I had been working on for a few-days with its autocomplete feature so I’m very grateful.

    But now I’d like to push things one-step further if possible – here’s the scenario:

    If I have a data set that includes things like the following:

    MEMORY DESKTOP DDR PC2100
    MEMORY LAPTOP DDR PC2100
    MEMORY DESKTOP DDR2 PC2-3200
    MEMORY LAPTOP DDR2 PC2-3200

    If I type in ‘desktop’ that has to be followed by DDR or the drop-down suggestions are removed.

    What I’d like to be able to do is type in ‘desktop’ followed by ‘pc2100′ for example which would leave only the entry that contains both words even though their not next to each other.

    Is this possible?

  24. balaji says:

    ur value get from array format, but how to get the value from data base , if possible tell me

  25. Loi Tran says:

    How I can add event submit form after selecting 1 item.
    I try
    select: function(event, ui){
    $(“#city”).val(ui.item.city);
    $(“#state”).val(ui.item.state);
    $(“#zip”).val(ui.item.zip);
    $(“formID”).submit();
    }

    But it doesn’t work,please help!

  26. Erik says:

    Add the # in front of “formID” like this:
    $(“#formID”).submit();

  27. Raynald says:

    This is exactly what I need for a site I’m developing but I have a limited knowledge of javascript and can’t get the code to work. Could you explain how to set up the files just to make it work like the example above or provide the actual zip file?

  28. Ben Smith says:

    Dear Erik

    I appreciate you’re trying to help people with this but I’m adding my voice to those who can’t get this to work…which is so frustrating. I’m not a PHP coder – could you please zip up a working solution – it must be the PHP file which isn’t working as have viewed source and copied it exactly…

    Thanks

    Ben

  29. Erik says:

    Raynald and Ben – The point of this tutorial isn’t to illustrate how to create the PHP code but instead to illustrate how to leverage the jQuery plugin to make your forms more intelligent and improve the overall user experience. The script that feeds the data to jQuery is only provided so you can use it as a starting point for generating your own data – not as a reference implementation. It simply shows one way to generate a response object that jQuery can use. You can cut and paste the code directly into your own editing environment and get started with it.

    It is possible to generate the response in a myriad of ways. For example, you can see in the comments some have used MySQL and a like clause and that code looks very different. The point is that there’s no “right” way to do it. In fact if you are using some sort of data source such as Redis, Memcached, or other storage engine, this may be the WRONG approach! The example was intentionally kept as minimal as possible using only simple structures in PHP so as to remain focused on the concepts it was attempting to illustrate – passing back json data to jQuery.

    The callback script provided as source in the original post will run on most current Linux distros with PHP 5.2 or newer installed. Your implementation of PHP may differ from mine, you may not have json_encode() available. If you are on an older version of PHP which will cause the code not to run. You can run php -v from the command line to see what version you are running. There are a lot of opensource and freely available JSON libraries that you can plug into PHP as well as Pecl extensions to bring support to older PHP versions.

  30. Ben Smith says:

    Erik – thank you so much for taking the time to provide that explanation. I’m contacting my server provider to check which version of PHP is being run.

    Kind regards

    Ben

  31. Tsekouras Nikos says:

    Thanks Eric,
    Your post was extremely helpfull and
    with no more things that needed

  32. shy says:

    hi there! :D this is the kind of form i’m looking for! :D but the problem is.. i really don’t know how to implement it using python pgsql. :(

  33. pat says:

    Hi, very useful!
    I have to fill a form about eight fields, but I want to show on the autocomplete menu only two fields.
    This Php code show all items on the menu:
    $city[‘label’] = “{$cognome} {$nome}, {$local}, {$domicilio} – {$telefono} {$prova} {$prova1} {$prova2}”;
    Is there any way to do this?
    Thanks

  34. James Daily says:

    @Todd_Young: you may need to split the input into an array by spaces, pass it as a “data” parameter (alongside select and source) and have your php file use the terms to return the truncated list.

    The jquery autocomplete operates in two ways – it can load an entire static list and filter it internally for you, or it can submit search term(s) via ajax to a custom stored procedure somewhere that performs the filtering and returns a custom result set.

    This site’s example does the static thing, it seems, while you’d need the Ajax.

  35. James Daily says:

    One improvement I’d appreciate is to have jquery ui auto-select the element in the list if the user typed enough to leave only one choice and then hits Tab to leave the field.

    I can’t think of a simple way to code this elegantly with the current autocomplete feature set.

  36. Thank you so much Erik, this post helped us a lot at work. You’ve just helped somebody from Honduras.

  37. Dev says:

    Using an implimentation like this.. i have 2 questions.. the first.. how can I have it get the JSON info from an external .php file? – Seems that would be more efficient for a large data base.

    And the second question. Each field. City/State/Zip. is there a way to assign a separate ID to each? that would get added to the database upon Submitting the form, instead of the actual text that is showing?

  38. Pingback: JQuery – Basic AutoComplete Example with Code « Justin Cooney – Programming Tips

  39. Kevin Strel says:

    Hi Erik,
    Works great, thank you for the contribution. Would it be possible to take this one step further and show how this would connect to a more complete remote data set? For example: Here is a JSON database of every city / state / zipcode in the USA: http://gomashup.com/cms/usa_zipcode_json

  40. Murtuza says:

    This is really incredible. Thanks Erik, I need a little more help though. In this case you are reading from database. do you have any hint or suggestion on how to read from an excel sheet?

    Thanks.

  41. Tim Wilson says:

    I know this is an old post, but others have recently commented so I will as well :)

    How do you clean up the other fields that are being set if the user ends up just going back and manually typing an entry in the City field that doesn’t show up in the results.

    Example:

    User types Detroit and picks Detroit from the list thus populating the rest of the fields. Then the user realized they actually wanted Detrumpt, CA so they go back and retype their entry but this one is not found so they manually enter it and continue.

    Now, all is fine and well if they continue and re-enter all the auto populated data, but if you are using this to set hidden fields (as I am trying to do) then you are going to have issues with incorrect data being passed when the page is submitted.

    Thoughts?

  42. Mark says:

    Did anyone ever get a modle of this working pulling from a database? Any help would be appreciated.

  43. brad says:

    thanks! i looked everywhere and this is the best example using the IDs and labels!

  44. Eman says:

    Hello,

    Im having trouble duplicating your code. I have copies both the php and html files in separate files. when i run the code three text fields appear in the screen with the css style, but the auto-complete is not working.

    My question is:
    in this part of the code
    source: “/ajax/demo_cities.php”
    am I supposed to create a folder ajax for the php file. Because I did and still not working? Please help me I really like this example and I think I can give use to it, but I need to get it working first.

  45. parameswaran vinayagam says:

    Dear Erik

    I want to search exact content don’t want to search full text search is there any option ???

    Thanks

    Parameswaran Vinayagam

  46. Siva Ramakrishnan says:

    sir i’m new in ajax with php mysql …please how to add,edit, delete data in a single form using ajax frame work….. help me

  47. Siva Ramakrishnan says:

    add like student bio data something and i fetch data using id key edit and delete in a single form using ajax with jqery ….help me

  48. roy says:

    hye sir.. can i ask u how to made dropdown list value from this autocomplete ?

  49. Tommy says:

    nice share..
    can I download the code?
    because i’ve been searching this code,but i couldn’t find it..
    thanks if you can send me the code..

  50. Parvani says:

    please help me how to query this output in MySQL DB?

    $cities = array(
    array('city'=>'New York', state=>'NY', zip=>'10001'),
    array('city'=>'Los Angeles', state=>'CA', zip=>'90001'),
    array('city'=>'Chicago', state=>'IL', zip=>'60601'),
    array('city'=>'Houston', state=>'TX', zip=>'77001'),
    array('city'=>'Phoenix', state=>'AZ', zip=>'85001'),
    array('city'=>'Philadelphia', state=>'PA', zip=>'19019'),
    array('city'=>'San Antonio', state=>'TX', zip=>'78201'),
    array('city'=>'Dallas', state=>'TX', zip=>'75201'),
    array('city'=>'San Diego', state=>'CA', zip=>'92101'),
    array('city'=>'San Jose', state=>'CA', zip=>'95101'),
    array('city'=>'Detroit', state=>'MI', zip=>'48201'),
    array('city'=>'San Francisco', state=>'CA', zip=>'94101'),
    array('city'=>'Jacksonville', state=>'FL', zip=>'32099'),
    array('city'=>'Indianapolis', state=>'IN', zip=>'46201'),
    array('city'=>'Austin', state=>'TX', zip=>'73301'),
    array('city'=>'Columbus', state=>'OH', zip=>'43085'),
    array('city'=>'Fort Worth', state=>'TX', zip=>'76101'),
    array('city'=>'Charlotte', state=>'NC', zip=>'28201'),
    array('city'=>'Memphis', state=>'TN', zip=>'37501'),
    array('city'=>'Baltimore', state=>'MD', zip=>'21201'),
    );

    Thank you

  51. Denis says:

    Hey, if anybody is still looking over the comments:

    I have some trouble implementing this and adding the mysql query for suggestions.

    If someone could just give me a link to a zip-file containing the right code i’d be most thankfully! =)

    Thanks in advance

  52. Thank you for the great tutorial, Erik! I just used it almost unaltered at my current project.

  53. Cognis says:

    Great example but I had trouble starting it and I see I’m not the only one. I did two things to make this work.

    Firstly in the demo_cities.php state and zip should be under single qoutes (‘state’, ‘zip’). Secondly I removed the / in the source so it wouldn’t be an absolute path and just left source:”demo_cities.php”, off course put your php file in the same folder as well. Hope it helps.

    This is pretty much what I needed and now I’m going to fiddle with it a little bit. Thanks again.

  54. sam says:

    Can anyone tell me how can i use this with jsp and servlet with database for populating/ auto filling multiple textbox

  55. manju says:

    i am happy with the above demo… but please help me out same thing using jsp

  56. Daniele says:

    thanks for your code.
    i’d like to make e redirect just after selecting a city by collecting the href value from my db

    $(document).ready(function(){
    var ac_config = {
    source: “test_auto_search2.php”,
    select: function(event, ui){
    $(“#localita”).val(ui.item.city);
    ——-example——
    href:”http://www.italy.it”;
    ————————
    },
    minLength:1
    };
    $(“#localita”).autocomplete(ac_config);
    });

    but how can i?

  57. Pingback: Using Bootstrap's Typeahead to populate a form with values from a MySQL database | BlogoSfera

  58. lloyd says:

    I had to put your field names in quotes, e.g —

    $cities = array(
    array(‘city’=>’New York’, ‘state’=>’NY’, ‘zip’=>’10001′),

    — and then your code worked fine.

    Thanks for your website – great help!

  59. Pingback: Autocomplete text from sql database - jQuery Solution - Developers Q & A

  60. Janardhan says:

    Hii,
    Im using jquery for autocomplete feature and getting data from database.Autocomplete is working fine but the problem is..when I select any option from the list, I need that option to be populate in the current page after pressing submit button.
    Im new to jquery….Any help is appriciated.

  61. Elie says:

    thanks for your code sir
    it amazing that what i was looking for it for while
    i tried to replace the array in php file with data from mysql <?php
    $host = "localhost";
    $uname = "root";
    $pass = "";
    $database = "db342183729";

    $connection=mysql_connect($host,$uname,$pass) or die("connection in not ready “);
    $result=mysql_select_db($database) or die(“database cannot be selected “);

    {
    $term=’oil';
    $sql = mysql_query (“SELECT * FROM customer WHERE CustomerCompanyName LIKE ‘%{$term}%'”);
    $array = array();
    while ($row = mysql_fetch_assoc($sql))
    {
    $array=array(‘city’=>$row[‘CustomerCompanyName’],’state’=>$row[‘CustomerCompanyName’],’zip’=>$row[‘id’],’value’=>$row[‘CustomerCurrency’],’label’=>$row[‘CustomerCurrency’]);
    }
    echo json_encode($array);
    }
    ?>

    but it didn’t work can you help me to modified please thanks

  62. Pingback: jQuery need automatically fill only one input field (row) based on value in other field (autocomplete); all other fields must remain unchanged | Technology & Programming

  63. Dante says:

    I’m not able to get it working after editing the code. What I did was changing the id y name of all the fields and php code. I.E. nombre replaced city, so in each appearence of city, I changed it. Is this incorrect? Am I missing something?

    This is my HTML:

    jQuery(document).ready(function(){
    var ac_config = {
    source: "datos.php",
    select: function(event, ui){
    jQuery("#nrocliente").val(ui.item.nrocliente);
    jQuery("#nombre").val(ui.item.nombre);
    jQuery("#apellido").val(ui.item.apellido);
    jQuery("#mensaje").val(ui.item.mensaje);
    },
    minLength:1
    };
    jQuery("#nombre").autocomplete(ac_config);
    });

    Nombre:

    Apellido:

    Mensaje:

    And this is my datos.php file:


    get_results('SELECT id AS nrocliente, nombre, apellido, mensaje FROM clientes');

    // Turns the array of objects into an array of arrays, exactly like the example

    $array = array();
    foreach($clientes as $cliente){
    $arrcli = (array) $cliente;
    $array[] = $arrcli;
    }

    //print_r($array);

    // Cleaning up the term
    $term = trim(strip_tags($_GET['term']));

    // Rudimentary search
    $matches = array();
    foreach($array as $data){
    if(stripos($data['nombre'], $term) !== false){
    // Add the necessary "value" and "label" fields and append to result set
    $data['value'] = $data['nombre'];
    $data['label'] = "{$data['nombre']}, {$data['apellido']} {$data['mensaje']}";
    $matches[] = $data;
    }
    }

    // Truncate, encode and return the results
    $matches = array_slice($matches, 0, 5);
    print json_encode($matches);
    ?>

  64. Dante says:

    The code was cropped :(
    Here’s a pastebin: http://pastebin.com/DUXaV1DC

    Please, take a look at it. I’d love some ideas about it.
    Oh, and the code work flawlessly if I just copy and paste it into WordPress without any modifications.

    Thanks in advance!

  65. Dante says:

    Hi again! Still looking into it but I suspect the problem is an empty Array as I call the WordPress function from a separate php file, I assume it doesn’t work that way.

    Do you know how can I integrate all the code in 1 php file? I assume the source in the following code must be modified but I don’t know what to put in there:


    var ac_config = {
    source: "datos.php",

  66. eagle says:

    Here is a sample to pull data from database.

    Follow links at your own risk: pan.baidu.com/s/1pJ8oPYF

  67. Pingback: Wowww! jQuery autocomplete tutorial with PHP and MySQL | Wowww!

  68. Vincent says:

    I have a issue with this and CSS formatting.

    I have a form with multiple input fields, where I use CSS to align it, I use:
    input,label{float:left;}

    But this creates an issue for the pop-up list of the autocomplete, it drops down the first line of the list to under the entire form.
    How can I prevent this?

  69. Alireza says:

    Hi
    Thank you it was great unless i used it in httpS:// pages.
    Do you have any idea how to set it for using in ssl protected pages?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>