I am moving the WooCommerce Coupon input field bellow order total by editing the review-order.php
Checkout Page using this method
but the problem is applying coupon with ajax is not working.
SO my goal is to implement the ajax feature on apply coupon.
So what I am trying
My PHP ajax action function
function implement_ajax_apply_coupon() {
global $woocommerce;
// Get the value of the coupon code
//$code = $_REQUEST['coupon_code'];
$code = filter_input( INPUT_POST, 'coupon_code', FILTER_DEFAULT );
// Check coupon code to make sure is not empty
if( empty( $code ) || !isset( $code ) ) {
// Build our response
$response = array(
'result' => 'error',
'message' => 'Code text field can not be empty.'
);
header( 'Content-Type: application/json' );
echo json_encode( $response );
// Always exit when doing ajax
exit();
}
// Create an instance of WC_Coupon with our code
$coupon = new WC_Coupon( $code );
// Check coupon to make determine if its valid or not
if( ! $coupon->id && ! isset( $coupon->id ) ) {
// Build our response
$response = array(
'result' => 'error',
'message' => 'Invalid code entered. Please try again.'
);
header( 'Content-Type: application/json' );
echo json_encode( $response );
// Always exit when doing ajax
exit();
} else {
if ( ! empty( $code ) && ! WC()->cart->has_discount( $code ) ){
WC()->cart->add_discount( $code ); // apply the coupon discount
// Build our response
$response = array(
'result' => 'success',
'message' => 'successfully added coupon code'
);
header( 'Content-Type: application/json' );
echo json_encode( $response );
// Always exit when doing ajax
exit();
}
}
}
add_action('wp_ajax_ajaxapplucoupon', 'implement_ajax_apply_coupon');
add_action('wp_ajax_nopriv_ajaxapplucoupon', 'implement_ajax_apply_coupon');
and My script is
( function($) {
$( document ).ready( function() {
$( '#apply_coupon').click( function( ev ) {
// Prevent the form from submitting
ev.preventDefault();
// Get the coupon code
var code = $( '#coupon_code').val();
var button = $( this );
data = {
action: 'ajaxapplucoupon',
coupon_code: code
};
button.html( 'wait.');
// Send it over to WordPress.
$.post( wc_checkout_params.ajax_url, data, function( returned_data ) {
if( returned_data.result == 'error' ) {
$( 'p.result' ).html( returned_data.message );
} else {
setTimeout(function(){
//reload with ajax
$(document.body).trigger('update_checkout');
button.html( 'Apply');
}, 2000);
console.log( returned_data+code );
}
})
});
});
})(jQuery);
My AJax Action function return nothing Please help.
2
Answers
Should be:
I know i am late, we got why submit not working .
As you shared article link – if we fallow the same then coupon code not working because you are using checkout coupon form inside checkout form means form within form so first remove form tag form coupon html and use like this:
Then add jquery either your custom.js file or directly on footer page like this:
Its working in my checkout page:
https://www.loom.com/share/7dfc833895d248f191ba327cf5290403