0

I'm looking for a simple example of some code showing how to use jquery autocomplete with ids and values, json and php, but I can't find any. Basically I have a list of employee names in a database, they have an id and a name. I would like to display the name, but use the id in a hidden field in my form submission. I would like to provide the list of names via php and json ajax. I would also like to use the feature where you have to enter say 3 characters before it shows the autocomplete, since it is a very long list of employee names. Not sure whether you have to pass the 3 characters to the php as a parameter for this.

I'm a noob so a simple example would really be appreciated.

Thanks

2
  • Google led me back to stackoverflow: stackoverflow.com/questions/5463577/… Commented Feb 2, 2012 at 20:53
  • Which isn't very helpfull to me, hence my question. Commented Feb 2, 2012 at 20:56

1 Answer 1

4

There are great examples here at jQuery UI: http://jqueryui.com/demos/autocomplete/#remote

Click the view source button below the example to get a look at the Javascript side of things. Note the parameters for "source" (this is the path to your PHP script delivering results) and "minLength." Setting the minLength property to 3 will take care of the second part of your question.

As far as the remote side the results need to be in JSON format so you can query your data from the database, get it as a PHP associative array and then use the json_encode() method to put it into a format that the autocomplete plugin can read. The autocomplete implementation in their example sends a querystring variable, "term", to the source file containing the search string input by the user.

This example expects JSON results from the server to be in this format: [ { "id": "Branta hrota", "label": "Pale-bellied Brent Goose", "value": "Pale-bellied Brent Goose" }, ...]

So the PHP source page could deliver results by using code like this:

// source.php (or whatever path you used for the autocomplete "source" setting)
// Sanitize your input!
$term = mysql_real_escape_string( $_GET['term'] );

$results = mysql_query( "SELECT * FROM employees WHERE name LIKE '%{$term}%' "); // Grab your data

$output_array = new array();

while ( $row = mysql_fetch_assoc( $results ) ) {
    $output_array[] = array( 
        'id' => $row['id']
        , 'label' => $row['name']
        , 'value' => $row['name']
    );
}

// Print out JSON response
echo json_encode( $output_array );

So that's all untested pseudocode, but it should point you in the right direction.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.