简体   繁体   中英

Query database in select onchange

I'd like to know how can I approach this better and what are my options. I cannot use AJAX requests for this.

I have a dropdown select populated through a SELECT query from the Database. The dropdown displays the user's display_name as the label and their IDs as the value. So:

$('select').val() retrieves an ID.

My problem is I'd like to display the selected user's username (another column from the same database table) in the onchange event of the Dropdown select.

Am I approaching this incorrectly?

EDIT:

I'm usiing Advanced Custom Functions for Wordpress, so this is how I'm retrieving my select and populating it:

function acf_load_color_field_choices( $field ) {
    $field['choices'] = array();

    foreach ($query as $row) {
        $field['choices'][$row[ID]] = $row[display_name];
    }

    return $field;
}
add_filter('acf/load_field/name=select_name', 'acf_load_color_field_choices');

Any idea if there's a way to add a data- attribute to this?

IMHO, the best approach as you can't use AJAX would be

  • You can actually fetch the username along with the query you use to populate the select.
  • Create an attribute in the option tags and fill the names from the query against the id's in the tags like <option data-name='Name' value='' ></option>
  • Fetch this attribute on change and your problem would be met

Since it was faster than figuring out if the plugin provided the data-name attribute, I managed to resolve my problem by changing my logic around.

Instead of passing the ID as a value, I've passed the username as a value. Then on the receiving end, I did a query to get the ID based on the username (since username is unique).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM