0

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>
<?php
      $results = $wpdb->get_results( "SELECT * FROM $table_name"); 
        foreach ( $results as $result ) {
            echo '<option  value="'.$result->id.'">'.$result->area_name.'</option>';
        }
      ?>
                 </select>
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($) {
    $(document).ready(function(){
    $('#mySelect').on( 'change' , function(){
        var newValue = $(this).val();
        $.ajax({
            type: 'POST',
            url: ajaxurl, // use ajax_params.ajax_url if using in plugin
            dataType: 'json',
            data: {
                action: 'yourFunction',
                newValue: newValue
            },
            success: function(response) {
                console.log(response);
            },
            error: function(errorThrown){
                console.log(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
wp_localize_script(
     'ajax-scripts',
'ajax_params',
array( 
    'ajax_url' => admin_url( 'admin-ajax.php' )
)
);
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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