我通过使用this method编辑review-order.php
结帐页面来移动WooCommerce优惠券输入字段的总订单量
,但问题是在ajax上应用优惠券不起作用。 所以我的目标是在apply coupon上实现ajax功能。
所以我正在尝试 我的PHP ajax操作函数
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');
我的脚本是
( 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);
我的AJax Action函数什么也不返回,请帮忙。
答案 0 :(得分:0)
data = {
action: 'ajaxapplucoupon',
coupon_code: code
};
应该是:
var data = {
action: 'ajaxapplucoupon',
coupon_code: code
};