How to Update Cart amount using Ajax in Woocommerce

When I was working on how to use Ajax on the checkout page. I used WordPress Ajax (wp_ajax_) but it was not working. After so many efforts I found a solution using  Woocommerce hook “woocommerce_review_order_before_payment “  and “woocommerce_cart_calculate_fees”. Let see how Update Cart amount using Ajax in Woocommerce  works with woocommercerce.

How woocommerce_review_order_before_payment hook works: If you want to  add custom checkout field after order total on checkout page you can use this hook. For example:

add_action( ‘woocommerce_review_order_before_payment’, ‘custom_checkout_field’);

function custom_checkout_field() {

echo ‘<div id=”custom_checkout_field”>’;

woocommerce_form_field( ‘discount’, array(

‘type’      => ‘checkbox’,

‘class’     => array(‘input-checkbox’),

‘label’     => __(‘Discount’),

),  WC()->checkout->get_value( ‘discount’ ) );

echo ‘</div>’;

}

you need to update checkout page when checked ‘input-checkbox’.  For that you need to add javascript:

<script type=”text/javascript”>

jQuery(document).ready(function() {

jQuery(‘.input-checkbox’).change(function() {

jQuery(‘body’).trigger(‘update_checkout’);

});

});

</script>

After that whenever you checked the ‘input-checkbox’, then checkout page automatically update by Ajax.

When checkout page update by Ajax, the Ajax sends ‘post_data’ in $_POST variable. All checkout field values store in ‘post_data’. You need to parse_str() for example:

Parse_str($_POST[‘post_data’], $post_data);

 

How woocommerce_cart_calculate_fees hook works: If you want to add custom fee in order, you need to use ‘woocommerce_cart_calculate_fees’ hook

add_action( ‘woocommerce_cart_calculate_fees’, ‘custom_wc_add_fee’);

 

function custom_wc_add_fee() {

global $woocommerce;

if (is_ajax() && !empty( $_POST[‘post_data’] ) ) {

parse_str( $_POST[‘post_data’], $post_data );

}else {

$post_data = $_POST;

}

 

if(!empty($post_data[‘discount’])){

$woocommerce->cart->add_fee( ‘Disount’,-20);

}

}