user1757383
user1757383

Reputation: 91

Getting ID from JQUERY Autocomplete

I have an autocomplete from JQUERY and I want the ID of the product instead of the name of the product that I am choosing.

This is the complete AUTOCOMPLETE:

    <?php

    // if the 'term' variable is not sent with the request, exit
    if ( !isset($_REQUEST['term']) )
    exit;

    // connect to the database server and select the appropriate database for use
    include 'conexion2.php';

    // query the database table for client codes that match 'term'
    $rs = mysql_query('SELECT id_cliente, nombrecliente FROM cliente where nombrecliente like "'. mysql_real_escape_string($_REQUEST['term']) .'%" order by nombrecliente asc', $conexio);

    // loop through each name returned and format the response for jQuery
$data = array();
    if ( $rs && mysql_num_rows($rs) )
    {
    while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
    {
        $data[] = array(
            'label' => $row['nombrecliente'],
            'value' => $row['nombrecliente'],
        );
    }
    }

    // jQuery wants JSON data
    echo json_encode($data);
    flush();

I dont know how to take out the ID when I choose a Client. If I change 'value' => $row['id_cliente'], then I get the ID number in my autocomplete INPUT....

Upvotes: 1

Views: 1164

Answers (1)

james_tookey
james_tookey

Reputation: 905

In your array, add in another item:

'id' => $row['id_cliente']

Then, you'll need to add a hidden form field which will store your ID. In your jQuery (assuming you're using jQueryUI autocomplete), you can add this underneath your source as part of the autocomplete function:

$('#autocomplete_input').autocomplete({
    source: '/path/to/lookup/php/file',
    select: function(event, ui){
        $('#my_hidden_field').val(ui.item.id);
    }
});

Then, when you read your form after submission you'll read that ID instead of the autocompleted field.

Upvotes: 1

Related Questions