Apply coupon code on Woocommerce checkout page with AJAX
I moved the Woocommerce coupon form by editing the
review-order.php
based on this method
I would like to know if it's possible to make the coupon code apply with AJAX (without reloading the page) like in the cart page. I don't know where to start, please help.
Solutions
as per your shared link , if you follow the same means you are using the coupon form inside the checkout form, so you should remove the coupon form tag and then use it.
-
Copy woocommerce review-order.php and past inside your active then woocommerce folder.
-
Open review-order.php and past coupon HTML inside table structure like this:
<tr class="coupon_checkout"> <td colspan="2"> <?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } if ( ! wc_coupons_enabled() ) { return; } ?> <a href="#" class="showcoupon"><i class="fa fa-plus"></i> REDEEM A PROMO CODE/GIFT VOUCHER</a> <div class="checkout_coupon" method="post" style="display:none"> <p class="form-row form-row-first"> <input type="text" name="coupon_code" class="input-text" placeholder="<?php esc_attr_e( 'Coupon code', 'woocommerce' ); ?>" id="checkout_coupon_code" value="" /> </p> <p class="form-row form-row-last"> <input id="checkout_apply_coupon" type="button" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply Coupon', 'woocommerce' ); ?>" /> </p> </div> </td> </tr> -
Add jQuery code either your custom.js file or directly on the footer page like this:
<script> jQuery(document).on('click','#checkout_apply_coupon', function() { // Get the coupon code var code = jQuery( '#checkout_coupon_code').val(); var button = jQuery( this ); data = { action: 'ajaxapplucoupon', coupon_code: code }; button.html( 'wait.'); // Send it over to WordPress. jQuery.post( wc_checkout_params.ajax_url, data, function( returned_data ) { if( returned_data.result == 'error' ) { jQuery( 'p.result' ).html( returned_data.message ); } else { setTimeout(function(){ //reload with ajax jQuery(document.body).trigger('update_checkout'); button.html( 'Apply'); }, 2000); console.log( returned_data+code ); } }) }); </script>
As i have tested on my checkout page it's working perfectly like this: https://www.loom.com/share/7dfc833895d248f191ba327cf5290403