Check WooCommerce coupon via Ajax


Here is how a WooCommerce coupon code can be checked for validity. The code below allows us to check WooCommerce coupon against the database. This is done using the inbuilt WC_Coupon class provided by WooCommerce.

The coupon code is sent to the function coupon_check_via_ajax(). The above function is AJAX enabled by registering it with wordpress AJAX using wp_ajax_* actions for both logged in and public users.

The Javascript
jQuery(function($){
    jQuery('input[name="check_coupon"]').on('click', function(){
    vardata= {
        'action':'check_coupon_via_ajax',
        'code':jQuery('input[name="coupon_code"]').val()
    };
    jQuery.post('/wp-admin/admin-ajax.php', data, function(response) {
        if(response.status==0){
            // -- ERROR
        } else {
            // -- SUCCESS
        }
        }, 'json');
    });
});
And the PHP code

function coupon_check_via_ajax(){ >

$code = strtolower(trim($_POST[‘code’]));
$coupon = new WC_Coupon($code);
$coupon_post = get_post($coupon->id);

if(!empty($coupon_post) && $coupon_post != null){
$message = ‘Coupon not valid’;
$status = 0;
if($coupon_post->post_status == ‘publish’){
$message = ‘Coupon validated’;
$status = 1;
}
} else {
$status = 0;
$message = ‘Coupon not found!’;
}

print json_encode( [ ‘status’ => $status, ‘message’ => $message, ‘poststatus’ =>               $coupon_post->post_status, ‘coupon_post’ => $coupon_post ] );
exit();
}

add_action( ‘wp_ajax_check_coupon_via_ajax’, ‘coupon_check_via_ajax’ );
add_action( ‘wp_ajax_nopriv_check_coupon_via_ajax’, ‘coupon_check_via_ajax’ );
[/php]

 

More wordpress articles located here
More about WC_Coupon from the WooCommerce documentation can be found here