How to Fetch values from WP database based on selected option value by onchange using PHP?

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' )
)
);