Home > Enterprise >  How to enable more than one fee with ajax in Woocommerce checkout?
How to enable more than one fee with ajax in Woocommerce checkout?

Time:06-29

I'm trying to add more than one fee to the order total amount checkout using ajax. So far, the first fee, insurance_shipping_fee, is working correctly, but when checking the second one, premium_gift_box, I receive a 400 error ("xxx.com/wp-admin/admin-ajax.php").

Any ideas on why? Any help appreciated

This is the full code:

// Calculate insurance fee
function as_calculate_insurance_fee() {
  $shipping_country = WC()->customer->get_shipping_country();
  $cart_subtotal = WC()->cart->subtotal;
  $cart_subtotal_rounded = ceil($cart_subtotal / 100) * 100;

  if($shipping_country == 'AU') {
    if($cart_subtotal <= 5000) $insurance_fee = $cart_subtotal_rounded/100   1;

  } else {
    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping = $chosen_methods[0];

    if ($chosen_shipping == 'free_shipping:12' || $chosen_shipping == 'starshipit_4') {
      if($cart_subtotal <= 5000) $insurance_fee = $cart_subtotal_rounded/100 * 3;

    } else if($chosen_shipping == 'starshipit_5') {
      $insurance_fee = ($cart_subtotal_rounded - 1000)/100 * 3   25;
    }
  }

  return $insurance_fee;
}
 
// Add a Shipping Insurance checkbox field
function add_custom_checkout_checkbox() {
  $insurance_fee = as_calculate_insurance_fee();
  if( WC()->session->get('enable_fee') ) $checked = true;
  else $checked = false;

  woocommerce_form_field( 'insurance_fee', array(
      'type'  => 'checkbox',
      'label' => __('<span ><bdi><span >'.get_woocommerce_currency().' </span>'.$insurance_fee.'</bdi></span>'),
      'class' => array( 'form-row-wide' ),
  ), $checked );
}

add_action( 'as_review_order_after_shipping', 'add_custom_checkout_checkbox', 20 );
 
// Add Signature Gift Box checkbox field
function add_custom_checkout_checkbox_2() {
  if( WC()->session->get('enable_fee_2') ) $checked = true;
  else $checked = false;

  woocommerce_form_field( 'premium_giftbox_fee', array(
      'type'  => 'checkbox',
      'label' => __('<span ><bdi><span >'.get_woocommerce_currency().' </span>9</bdi></span>'),
      'class' => array( 'form-row-wide' ),
  ), $checked );
}

add_action( 'as_review_order_before_shipping', 'add_custom_checkout_checkbox_2', 20 );

// Add custom fees
function custom_fee( $cart ) {
  // Only on checkout
  if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
    return;

  $insurance_fee = as_calculate_insurance_fee();

  if( WC()->session->get('enable_fee') )
    $cart->add_fee( __( 'Insurance fee', 'woocommerce'), $insurance_fee );

  if( WC()->session->get('enable_fee_2') )
    $cart->add_fee( __( 'Siganture Gift Box fee', 'woocommerce'), 9 );
}

add_action( 'woocommerce_cart_calculate_fees', 'custom_fee', 20, 1 );

// Remove "(optional)" label on checkbox field
function remove_order_comments_optional_fields_label( $field, $key, $args, $value ) {
  // Only on checkout page for Order notes field
  if( ( 'insurance_fee' === $key || 'premium_giftbox_fee' === $key ) && is_checkout() ) {
    $optional = '&nbsp;<span >(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
    $field = str_replace( $optional, '', $field );
  }
  return $field;
}

add_filter( 'woocommerce_form_field' , 'remove_order_comments_optional_fields_label', 10, 4 );

// jQuery - Ajax script
function checkout_fees_script() {
  // Only on Checkout
  if( is_checkout() && ! is_wc_endpoint_url() ) :

  if( WC()->session->__isset('enable_fee') )
      WC()->session->__unset('enable_fee');

  if( WC()->session->__isset('enable_fee_2') )
      WC()->session->__unset('enable_fee_2');
  ?>
  <script type="text/javascript">
  jQuery( function($){
    if (typeof wc_checkout_params === 'undefined') 
      return false;

    $('form.checkout').on('change', 'input[name=insurance_fee]', function(e){
      var fee = $(this).prop('checked') === true ? '1' : '';

      $.ajax({
        type: 'POST',
        url: wc_checkout_params.ajax_url,
        data: {
          'action': 'enable_fee',
          'enable_fee': fee,
        },
        success: function (result) {
          $('body').trigger('update_checkout');
        },
      });
    });

    $('form.checkout').on('change', 'input[name=premium_giftbox_fee]', function(e){
      var fee2 = $(this).prop('checked') === true ? '1' : '';

      $.ajax({
        type: 'POST',
        url: wc_checkout_params.ajax_url,
        data: {
          'action': 'enable_fee_2',
          'enable_fee_2': fee2,
        },
        success: function (result) {
          $('body').trigger('update_checkout');
        },
      });
    });
  });
  </script>
  <?php
  endif;
}

add_action( 'wp_footer', 'checkout_fees_script' );

// Get Ajax request and saving to WC session
function get_enable_fee() {
  if ( isset($_POST['enable_fee']) ) {
    WC()->session->set('enable_fee', ($_POST['enable_fee'] ? true : false) );
  }

  if ( isset($_POST['enable_fee_2']) ) {
    WC()->session->set('enable_fee_2', ($_POST['enable_fee_2'] ? true : false) );
  }

  die();
}

add_action( 'wp_ajax_enable_fee', 'get_enable_fee' );
add_action( 'wp_ajax_nopriv_enable_fee', 'get_enable_fee' );

    ```

CodePudding user response:

You forgot to register the second fee ajax action. It should be like that.

add_action( 'wp_ajax_enable_fee', 'get_enable_fee' );
add_action( 'wp_ajax_nopriv_enable_fee', 'get_enable_fee' );

add_action( 'wp_ajax_enable_fee_2', 'get_enable_fee' );
add_action( 'wp_ajax_nopriv_enable_fee_2', 'get_enable_fee' );
  • Related