March

29

jQuery UI Autocomplete Widget with PHP and MySQL

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.
autocomplete
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:

<link type="text/css" href="jquery-ui-1.8rc3.custom.css" rel="stylesheet" /> 

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8rc3.custom.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="submit" 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.

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:

  1. It queries the database
  2. Loops an array of the query results adding each row to a return array
  3. 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. And, of course, you will have to make your own connection to your MySQL database before running the query.

$return_arr = array();

$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);

/* If connection to database, run sql statement. */
if ($conn)
{
	$fetch = mysql_query("SELECT * FROM states where state like '%" . $_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);

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.”

$return_arr = array();

/* If connection to database, run sql statement. */
if ($conn)
{
	$fetch = mysql_query("SELECT * FROM states where state like '%" . $_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:

Demo

Download zip of all files

 

Further Reading:

  1. Using jQuery Autocomplete to Populate Another Autocomplete – ASP.NET, ColdFusion, and PHP Examples
  2. jQuery UI Autocomplete Widget with ASP.NET VB
  3. jQuery UI Autocomplete Widget with ColdFusion
  4. jQuery.ajax and jQuery.post Form Submit Examples with PHP

37 Comments for jQuery UI Autocomplete Widget with PHP and MySQL

[...] This post was mentioned on Twitter by JQuery Watcher, Larry King. Larry King said: jQuery UI Autocomplete Widget with PHP and MySQL – jensbits.com http://bit.ly/cbkzkP #jQuery [...]


Barbara
April 16, 2010

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


jen
April 16, 2010

@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


Barbara
April 17, 2010

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


jen
April 17, 2010

@Barbara
Are you running PHP 5?


Barbara
April 17, 2010

Yes. phpinfo() says 5.3.1.


jen
April 17, 2010

@Barbara
OK. Look at PHP info and make sure json support is enabled and that it's at least version 1.2.0.


Barbara
April 18, 2010

Hi Jen,

json is enabled, version is 1.2.1

Thank you!
Barbara


cx
April 20, 2010

Not really working for me either.


jen
April 20, 2010

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.


cx
April 20, 2010

Nevermind had the ui script above jquery.


Barbara
April 21, 2010

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


Surya Dewangga
May 1, 2010

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…


jen
May 1, 2010

@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!


Fybo
May 3, 2010

In the code, where jQuery script passes the value "term" (via GET request) to PHP script? I can't find…
Thanks a lot.


jen
May 3, 2010

@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.


Fybo
May 3, 2010

@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. :)


and
May 19, 2010

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.


Ramiro
May 24, 2010

Thanks a lot sharing this article is very useful is the best I found


jen
May 24, 2010

@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.


and
May 24, 2010

yess.. have you an idea? because i am writing a script that not works :'( !


e-media
May 28, 2010

Good article, and very good web site in general !

Very good idea to write an article of populating a second autocomplete by the result of the first one.

I think, it will get a good audience.

Bye


Jeremy
June 15, 2010

Hi, great script works like a charm. I have a question that is more related to design I suppose.

I am using this for a form within a table. Wen the autosuggest list comes up it moves all elements down to make room for the suggestions. Though in your demo it is overlayed. I was wondering what I'm missing to get the same effect.

Thanks!


jen
June 15, 2010

@Jeremy
It is hard to tell without a test page. If you can send a link, I take a look.


rafi
June 17, 2010

great tutorial thanks a lot


Jonathan
August 4, 2010

Thank you very much for this tutorial. Definitely the best I could find on the web.

This should be on the jquery UI page to give a better understanding on how functions the new autocomplete.

Anyway, thanks a lot !


Trevor
August 9, 2010

Perfect. Exactly what I needed. Thanks very much you good internet contributing soul.


Rich
August 13, 2010

Hi, please excuse my ignorance, but i am new to programming! Im trying to use the jquery auto-complete and its not quite working! when i type something in, the autocomplete box does appear to pop up….but is only a few mm high and doesnt contain anything. Any ideas or suggestions. My php is bringing something back from the database, in this format:
[{"id":"17","serial_no":"NA","dep_type":"RB"}] is this correct?


jen
August 13, 2010

@Rich
Sounds like the CSS is not working properly. Make sure you have the jquery ui stylesheet loading and that it is not conflicting with any other stylesheets.


Neal
August 26, 2010

I've got this in a file called keyword.php :
<?php
$return_arr = array();

$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$dbname = '';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);

if ($conn)
{

$fetch = mysql_query("SELECT optional_field_1 FROM geodesic_classifieds where title like '%" . $_GET['term'] . "%'");

/* Retrieve and store in array the results of the query.*/

while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['value'] = $row['optional_field_1'];
$row_array['label'] = $row['optional_field_1'];

array_push($return_arr,$row_array);

}
}
else
{

$row_array['value'] = "none";
$row_array['label'] = "none";

array_push($return_arr,$row_array);
}

/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($return_arr);

?>

And modified the index.php file with this:
$("#state_abbrev").autocomplete({
source: "keyword.php",
minLength: 2
});

I took the db login info out of the top file to display. Other than that do you see anything wrong with these? I can't get it to show any drop down or suggestions. I have php 5.2.9 and json 1.2.1.

Thanks for the help. This is a great little tool.


jen
August 27, 2010

@Neal
Nothing jumps out at me. If you have Firebug, can see the response and that may help debug. If you have a test page online, I can look at that for you.


Neal
August 27, 2010

Thanks
I've got it working now. The field that I'm telling it to get suggestions from has the same value for more than one record, so when I typed in a few letters to trigger the suggestions, two of the same suggestions came up. How could I prevent this?

Thanks


Neal Lassiter
August 29, 2010

I have been working on integrating this into the website and am getting an error now. I think this has to do with putting it in a system that runs on smarty. With firebug, I get this error:
b is null
[Break on this error] (function(a){a.widget("ui.autocomplete…ull,{item:this.active})}})})(jQuery);;

It works fine here: http://bamabuy.com/search.php
I am having trouble here in the top search box: http://bamabuy.com/

The one that works doesn't use smarty.


John B
September 4, 2010

When you use $_GET['term'] what is term? Doesn't term have to be the name of one of the elements in the HTML? I do not see it anywhere in there. Is this a bug or is term some generic construct I'm not aware of?

Thanks,

John


jen
September 4, 2010

@John B
Term is sent by the jquery autocomplete itself as a get variable to the source page you specify. If you install Firebug, you can see the get called by jquery.


mbrad
September 4, 2010

Hi Jen,
First of all, thanks to you for this tutorial. It's great people like you that are such a big help to the rest of us that are trying to learn.

I believe that I've implemented my autocomplete as you have instructed, but when I type in a value in my <input />, nothing happens. I have tested my sql stmt in phpMyAdmin, I get values. I've done an echo on my UserList.php which is the page that creates the array of User Names for the form to be placed in id="upduser".

This is my jquery function adjusted for my form:
<script type="text/javascript">
$(function() {
$("#upduser").autocomplete({
source: "UserList.php",
minLength: 2
//select: function(event, ui) {
// $('#upduser').val(ui.item.upduser);
//}
});
});
</script>
Have I left something out?

This is my form:
<h3><a href="#">Update User Level</a></h3>
<div>
<?php echo $form->error("upduser"); ?>

<form action="test.php" method="POST">
<span class="ui-widget"><label for="upduser">Username:</label>
<input class="txt" type="text" id="upduser" name="upduser" maxlength="30" value="<?php echo $form->value("upduser"); ?>" />
</span>
<label for="updlevel">Level:</label>
<select class="txt" id="updlevel" name="updlevel">
<option value="1">1</option>
<option value="9">9</option>
</select>
<br /><br />
<input type="hidden" name="subupdlevel" value="1" />
<input class="btn" type="submit" value="Update Level" />
</form>
</div>

Not sure what I've left out.
Thanks again for this great tutorial.
mbrad

Leave a comment

Why ask?

 

« | »