I am trying make it when user changes the Shipping address select dropdown it dynamically add a fee to cart totals using ajax.I could able to to get the value but when select a another state it wont update the totals.
My ajax request:
jQuery(document).ready(function () {
jQuery('#shipping_state').change(function () {
var data = {
action: 'woocommerce_custom_fee',
security: wc_checkout_params.update_order_review_nonce,
add_order_fee: 'state',
post_data: jQuery('form.checkout').serialize()
};
jQuery.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: data,
success: function (code) {
var result = '';
result = jQuery.parseJSON(code);
if (result.result === 'success') {
jQuery('body').trigger('update_checkout');
}
},
dataType: 'html'
});
return false;
});
})
add_action('woocommerce_cart_calculate_fees', 'woo_add_cart_fee');
function woo_add_cart_fee() {
global $woocommerce;
$destsuburb = $woocommerce->customer->get_shipping_state();
/*Then I use $destsuburb as a variable to API and get a shipping cost returning $shipping_cost*/
$woocommerce->cart->add_fee('Shipping and Handling:', $shipping_cost);
}
I am getting different Shipping cost according to the State,but its not changing the front end value through add_fee()
Finally I found a solution using a session variable to store the Ajax value and add_fee()
My ajax request:
And in functions.php