pee2pee
pee2pee

Reputation: 3792

jQuery Autocomplete - Show Data Based on Selection

I have a standard jQuery autocomplete setup similar to the below:

$("input#autocomplete").autocomplete({
    source: source,
    minLength: 5 ,
    select: function( event, ui ) {
         alert(ui.item.value);
    }
});

What I would like is, when the value is chosen, a data-table within the page appears and get populated with data from a database using the value as a search parameter.

So for instance if I select "RED", the table would then show and display data from a query such as SELECT * FROM TABLE WHERE COLUMN='RED'

The query is simplified but can anyone please point me in the right direction?

Upvotes: 0

Views: 1434

Answers (2)

Purag
Purag

Reputation: 17061

If I understand you correctly, you're looking for $.post.

For example, your jQuery would be:

$("input#autocomplete").autocomplete({
    source: source,
    minLength: 5 ,
    select: function( event, ui ) {
        $.post("autocomplete.php", { option: ui.item.value }, function(data){
            $("table").html( data[0] );
            // sets the content of a table element to the first matched row
        });
    }
});

And in autocomplete.php, you would have something like this:

// DB connect

// use $_POST['option'] here for the selected option
$sth = mysql_query("SELECT ...");
$r = mysql_fetch_assoc($sth);
print $r;

What we do here is request the page autocomplete.php and POST the data, which in this case is the selected value. autocomplete.php grabs that POSTed value and searches the database (you can customize that query to fit your needs). The page then prints an array of the matched rows, which is the data received by the jQuery, and can be traversed as a Javascript array.

Upvotes: 0

Paul T. Rawkeen
Paul T. Rawkeen

Reputation: 4114

For this purpose you should request a kind of search page which will act as JSON endpoint for e.g.

$("input#autocomplete").autocomplete({
    source: source,
    minLength: 5 ,
    select: function( event, ui ) {

      var _value = ui.item.value;

      $.post('services/populate_table.php', // endpoint URL
             { someParameterToTransmit: _value  }, // some data to transmit
             function(data) { // on complete handler
               $('.result').html(data); // populate retrieved data in any form you need
             } // on complete function
      ); // post
    } // on select (autocomplete)
}); // autocomplete

Data from endpoint also can be retrieved as JSON.

You can read documentation for more information about request method.

Upvotes: 2

Related Questions