I have retrieve data from WP db and display in select list. But I cant able to store the selected option value in php variable. And I cant able to display data based on selected value. The data should be displayed when the select box is changed (onChange)

<select id="mySelect" name="taskOption">
<option>Choose Your Area</option>
      $results = $wpdb->get_results( "SELECT * FROM $table_name"); 
        foreach ( $results as $result ) {
            echo '<option  value="'.$result->id.'">'.$result->area_name.'</option>';

1 Answer 1


You can use below example to use Ajax in wordpress. This article explains it quite nicely.

  1. Main jquery function to use

    wp_enqueue_script( 'ajax-scripts', url-to-your-file/plugin-ajax.js', __FILE__ ) , array( 'jquery' ), '1.0.0', true );
    jQuery(function($) {
    $('#mySelect').on( 'change' , function(){
        var newValue = $(this).val();
            type: 'POST',
            url: ajaxurl, // use ajax_params.ajax_url if using in plugin
            dataType: 'json',
            data: {
                action: 'yourFunction',
                newValue: newValue
            success: function(response) {
            error: function(errorThrown){
  2. Hook your function

    add_action( 'wp_ajax_yourFunction', 'yourFunction' );
    function yourFunction(){
        $newValue = $_POST['newValue'];
        //Query whatever you want to with the $newValue

If you're using it in a plugin then you'll need to localize your script first.

//Localize the script for ajax purposes
    'ajax_url' => admin_url( 'admin-ajax.php' )
  • Thanks Bro, but I cant able use this variable " $newValue" in other function Nov 15, 2017 at 6:56
  • you can use the $_POST[''] value in your query Nov 15, 2017 at 6:58
  • I have tried a lot. I want to use that variable in another function. pls post the example please Nov 15, 2017 at 7:16
  • Lets continue here chat.stackexchange.com/rooms/68741/wordpress-ajax Nov 15, 2017 at 7:18
  • using this setting helped for me... url: '/wp-admin/admin-ajax.php', Feb 16, 2022 at 1:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.