skip to Main Content

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.

2

Answers


  1. 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.

    1. Copy woocommerce review-order.php and past inside your active then woocommerce folder.

    2. 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>
      
    3. 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

    1. Optional (if not setup wp_localize_script yet then add into functions.php)

       function custom_enqueue() {
          wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/custom.js', array('jquery') ); // optional - if you want to add custom.js then goto theme directory- > js -> and create/add custom.js file 
          wp_localize_script( 'ajax-script', 'wc_checkout_params', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); // setup ajax call url
       }
       add_action( 'wp_enqueue_scripts', 'custom_enqueue' );
      
    Login or Signup to reply.
  2. You can modify the snippet below to match your styles.

    1. Place the coupon form below in review-order.php or include it from a separate file

      <form class="checkout_coupon m-0 p-0 border-0 woocommerce-form-coupon grid grid-cols-3" action="<?php echo esc_url(wc_get_cart_url()); ?>" method="post">
          <input type="text" name="coupon_code" class="input-text col-span-2" placeholder="<?php esc_attr_e('Coupon code', 'woocommerce'); ?>" id="coupon_code" value=""/>
          <button type="submit" class="theme-button-secondary" name="apply_coupon"><i class="fas fa-arrow-right"></i></button>
      </form>
      <script>
        jQuery(document).on('submit', 'form.checkout_coupon', function (e) {
          e.preventDefault()
          var form = jQuery(this)
          form.block({message: null, overlayCSS: {background: '#FFF', opacity: 0.6}})
          jQuery.post(wc_checkout_params.ajax_url, {
            action: 'ajax_apply_coupon',
            coupon_code: form.find('[name="coupon_code"]').val()
          }).done(function () {
            jQuery(document.body).trigger('update_checkout')
            form.unblock()
          }).fail(function (data) {
            jQuery(document.body).trigger('update_checkout')
            form.unblock()
          })
        })
      </script>
      

      If you want to include it from different file use this

      add_action('woocommerce_review_order_after_cart_contents', function () {
          if (is_checkout()) {
              wc_get_template('checkout/coupon.php');
          }
      }); 
      
    2. Add your ajax handler with the coupon logic in your function.php

       function ajax_apply_coupon()
       {
           $coupon_code = null;
           if (!empty($_POST['coupon_code'])) {
               $coupon_code = sanitize_key($_POST['coupon_code']);
           }
           $coupon_id = wc_get_coupon_id_by_code($coupon_code);
           if (empty($coupon_id)) {
               wc_add_notice(__('Sorry, there has been an error.', 'woocommerce'), 'error');
               wp_send_json_error(['message' => __('Sorry, there has been an error.', 'woocommerce')], 400);
           }
      
           if (!WC()->cart->has_discount($coupon_code)) {
               WC()->cart->add_discount($coupon_code);
           }
           wp_send_json_success(['message' => __('Coupon code applied successfully.', 'woocommerce')], 200);
       }
      
       add_action('wp_ajax_ajax_apply_coupon', 'ajax_apply_coupon');
       add_action('wp_ajax_nopriv_ajax_apply_coupon', 'ajax_apply_coupon'); 
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search