You might also be interested in the Using jQuery Autocomplete to Populate Another Autocomplete post.
As a follow up to the jQuery UI Autocomplete Widget with ColdFusion post, I did one with PHP as the backend.
The jQuery UI folks have released an autocomplete widget that is pretty slick. This example uses the json_encode function in PHP 5. If you have an earlier version of PHP, you will have to roll your own JSON string.

This example will use US states and territories to populate the autocomplete. It will also demonstrate how to fill other fields with data returned from the database. This data can be used to fill a visible text box or a hidden form field. It also demonstrates the basic autocomplete functionality which may be fine for some applications.
Of course, you will need the jQuery core file, the jQuery UI core file, and the jQuery UI style sheet of choice. The style sheet comes from the themes available in the jQuery UI website and can be downloaded with the core file or you can link to the latest versions of both the core files and the css:
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
The HTML is straight forward and stripped down for the example:
<form action="<?php echo $PHP_SELF;?>" method="post"> <fieldset> <legend>jQuery UI Autocomplete Example - PHP Backend</legend> <p>Start typing the name of a state or territory of the United States</p> <p class="ui-widget"> <label for="state">State (abbreviation in separate field): </label> <input type="text" id="state" name="state" /> <input readonly="readonly" type="text" id="abbrev" name="abbrev" maxlength="2" size="2"/></p> <input type="hidden" id="state_id" name="state_id" /> <p class="ui-widget"> <label for="state_abbrev">State (replaced with abbreviation): </label> <input type="text" id="state_abbrev" name="state_abbrev" /></p> <p><input type="submit" name="submitBtn" value="Submit" /></p> </fieldset> </form>
As a bonus, we dump out the form values to see what we have right underneath the form itself:
<?php
if (isset($_POST['submit'])) {
echo "<p>";
while (list($key,$value) = each($_POST)){
echo "<strong>" . $key . "</strong> = ".$value."<br />";
}
echo "</p>";
}
?>
And the jQuery on the page is equally brief:
$(function() {
$('#abbrev').val("");
$("#state").autocomplete({
source: "states.php",
minLength: 2,
select: function(event, ui) {
$('#state_id').val(ui.item.id);
$('#abbrev').val(ui.item.abbrev);
}
});
$("#state_abbrev").autocomplete({
source: "states_abbrev.php",
minLength: 2
});
});
Notice that there are two autocomplete functions on the page, one for each example in the demo. Each function calls a different PHP file which return slightly different result sets.
The jquery autocomplete will append the text typed into the autocomplete field as the URL parameter ‘term.’ This URL parameter is used to query the database.
From the jquery documentation:
The request parameter “term” gets added to that URL.
Also, the minLength for autocomplete to return results is set to 2 to prevent too many rows from being returned.
Both PHP pages return the data after a few steps:
- It queries the database
- Loops an array of the query results adding each row to a return array
- Outputs the array as JSON data
The states.php file returns the id field, the state field as ‘value’, and the abbrev field. These values are placed in the appropriate text boxes by the autocomplete jQuery function.
A ‘value’ and/or a ‘label’ field is mandatory for the autocomplete to work. See explanation at bottom of post.
And, of course, you will have to make your own connection to your MySQL database before running the query.
PDO version:
/* Connection vars here for example only. Consider a more secure method. */
$dbhost = 'YOUR_SERVER';
$dbuser = 'YOUR_USERNAME';
$dbpass = 'YOUR_PASSWORD';
$dbname = 'YOUR_DATABASE_NAME';
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$query = "SELECT * FROM states where state like :term";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['value'] = $row['state'];
$row_array['abbrev'] = $row['abbrev'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
Non-PDO version:
/* Connection vars here for example only. Consider a more secure method. */
$dbhost = 'YOUR_SERVER';
$dbuser = 'YOUR_USERNAME';
$dbpass = 'YOUR_PASSWORD';
$dbname = 'YOUR_DATABASE_NAME';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
$return_arr = array();
/* If connection to database, run sql statement. */
if ($conn)
{
$fetch = mysql_query("SELECT * FROM states where state like '%" . mysql_real_escape_string($_GET['term']) . "%'");
/* Retrieve and store in array the results of the query.*/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['value'] = $row['state'];
$row_array['abbrev'] = $row['abbrev'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
Very important information below. Please read and understand before expecting the autocomplete to work properly.
The states_abbrev.php shows the basic functionality of the autocomplete function by just assigning results of the query to the ‘label’ and ‘value’ fields. Explanation on the ‘label’ and ‘value’ fields from the jQuery UI site:
“The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.”
PDO version:
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$query = "SELECT * FROM states where state like :term";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['label'] = $row['state'];
$row_array['value'] = $row['abbrev'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
Non-PDO version:
$return_arr = array();
/* If connection to database, run sql statement. */
if ($conn)
{
$fetch = mysql_query("SELECT * FROM states where state like '%" . mysql_real_escape_string($_GET['term']) . "%'");
/* Retrieve and store in array the results of the query.*/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['label'] = $row['state'];
$row_array['value'] = $row['abbrev'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
Usual recommended jQuery and PHP reading:
If this post helped you out, please consider donating to help pay the hosting fees. 100% of the donations go to the web host.


Twitter
About
143 Comments
Pingback: Tweets that mention jQuery UI Autocomplete Widget with PHP and MySQL - jensbits.com -- Topsy.com
Hi,
thanks for this easy-to-follow description! It was the best I found on the Web so far! I have one problem though, and hopefully you can help me out…
I tried to run your example on my PC (on my Apache web-server), and I just don't get the result out of PHP. I added some error_log()-calls in the PHP-code to see what's happening. I can see that my PHP-script receives the requst and fills the $return_arr with the data from the DB, everything looks fine. But for some reason the resulting data is never shown in the browser (the autocomplete is just never populated). I can see the circle spinning that tells me to wait – and that's it. Just as if the PHP-script never returned or didn't deliver the data.
When I run the demo on your page it runs perfectly – so it cant' be the browser's fault. I copied everything from your page (HTML, CSS and PHP), so the code should be exactly the same. I also have the same versions of jQuery and jQuery-UI. I'm using XAMPP 1.7.3 on Windows 7 (64 bit).
Have you got any idea what the problem could be? Some settings in my web-server? Am I missing something important? I have a few month's experience with PHP, but am new to jQuery…
Thank you in advance for your help!
Kind Regards
Barbara
@Barbara
Are you connecting to your database? You have to set up your own connection (the $conn variable in the example) before results can be returned.
Check out this tutorial on how to do that:
http://bit.ly/ZVuk5
Hi Jen,
connection to the database is fine. To make sure that reading from the database works, I log the result using var_export() before returning from the PHP-script, like so:
…
error_log(var_export($return_arr,true),0);
print json_encode($return_arr);
I can see all the data in the log.
Now I have copied the files to OpenSuse (V 11.1, 32 bit), and there it works without any problems! I wonder why it doesn't work on my Windows 7???
Have you heard of any configuration issues I need to consider?
Thanks again!
Barbara
@Barbara
Are you running PHP 5?
Yes. phpinfo() says 5.3.1.
@Barbara
OK. Look at PHP info and make sure json support is enabled and that it's at least version 1.2.0.
Hi Jen,
json is enabled, version is 1.2.1
Thank you!
Barbara
Not really working for me either.
If you are having issues, an explanation would help.
Unfortunately, I cannot duplicate every possible server configuration and test the example out. I run Windows Server 2008 and OS 10.5 on two separate machines. Not to mention my web host which is Linux. All examples are tested on those three environments.
Remember, I post these examples free of charge to help you. If they do not work for you, I am sorry. You can return them for a full refund.
Nevermind had the ui script above jquery.
Hi Jen,
I didn't want you to test all possible configurations. I was just wondering if you knew of any problems with specific configurations. If I ever find out why it doesn't work on my Windows installation, I will leave a comment…
Barbara
thank you very much for your tuts, IT WORKS !!! Thank you very much,
May I translate your tuts into Indonesian??? We have a less tutorial about jQueryUi..
Surya Dewangga
Keep Posting…
@Surya
Feel free to translate any that you want. Please include a link to the original post in the translation and send me the link to the translated version so I can link to it from the original post.
Thank you!
In the code, where jQuery script passes the value "term" (via GET request) to PHP script? I can't find…
Thanks a lot.
@Fybo
The jquery autocomplete makes the get request. It appends it to the page you specify as the source in the autocomplete function. If you have Firefox, add the Firebug extension and you can see the get request in Firebug's console.
@jen
Thanks a lot for your reply, I didn't know so much about the autosuggestion widget. Now I'm decently skilled, thank you again.
hi, i have read your example of autocomplete-populate.. 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 canada and populate the form in the other form i want the other values related canada of the other table..
excuse me for my bad english.. i wait your help.thanks.
Thanks a lot sharing this article is very useful is the best I found
@and
I think you are talking about populating a second autocomplete based on the selection in the first autocomplete. If that is correct, I can work on an example for a future post.
@Ramiro
You are welcome! Thanks.