WooCommerce add a custom fee using ajax to cart totals on checkout page WooCommerce add a custom fee using ajax to cart totals on checkout page wordpress wordpress

WooCommerce add a custom fee using ajax to cart totals on checkout page


Finally I found a solution using a session variable to store the Ajax value and add_fee()

My ajax request:

jQuery(document).ready(function () {    jQuery('#State').click(function () {        if (jQuery('#ship-to-different-address-checkbox').is(':checked')) {            var state = jQuery('#shipping_state').val();            var post_code = jQuery('#shipping_postcode').val();        } else {            var state = jQuery('#billing_state').val();            var post_code = jQuery('#billing_postcode').val();        }        console.log(state + post_code);        var data = {            action: 'woocommerce_apply_state',            security: wc_checkout_params.apply_state_nonce,            state: state,            post_code: post_code        };        jQuery.ajax({            type: 'POST',            url: wc_checkout_params.ajax_url,            data: data,            success: function (code) {                console.log(code);//                jQuery('.woocommerce-error, .woocommerce-message').remove();                if (code === '0') {//                    $form.before(code);                    jQuery('body').trigger('update_checkout');                }            },            dataType: 'html'        });        return false;    });});