Woocommerce: Hide Other Shipping Rate When COD Payment Gateway Selected

i found this code, you can use, but it’s not working if you use thirdparty plugin like table rate..please use snippet plugin if you don’t know how to install..

PHP CODE:

// Assuming you're working in WordPress or some other PHP-based system with WooCommerce

// Enqueue the script in your theme's functions.php or a custom plugin file
function enqueue_custom_script() {
    wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery'), null, true);

    // Pass the URL to admin-ajax.php to your script
    wp_localize_script('custom-script', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'enqueue_custom_script');

// Add an action to handle the AJAX request
function handle_cod_selection() {
    // Check if the COD payment method is selected
    if ($_POST['payment_method'] == 'cod') {
        // If COD is selected, hide the shipping options
        update_option('woocommerce_ship_to_countries', 'disabled');
    } else {
        // If another payment method is selected, show the shipping options
        update_option('woocommerce_ship_to_countries', 'all');
    }
    
    die(); // This is required to return a proper result
}
add_action('wp_ajax_handle_cod_selection', 'handle_cod_selection');
add_action('wp_ajax_nopriv_handle_cod_selection', 'handle_cod_selection');

JS CODE:

jQuery(document).ready(function ($) {
    // Listen for changes in the payment method
    $('form.checkout').on('change', 'input[name="payment_method"]', function () {
        var paymentMethod = $(this).val();

        // Perform an AJAX request to handle the payment method selection
        $.ajax({
            type: 'post',
            url: ajax_object.ajax_url,
            data: {
                action: 'handle_cod_selection',
                payment_method: paymentMethod
            },
            success: function (response) {
                // Handle the success response if needed
                console.log(response);
            }
        });
    });
});

Hide all shipping rate when choose cod payment