Solution:
Use following code
add_action('wp_ajax_wc_woocommerce_clear_cart_url', 'wc_woocommerce_clear_cart_url');
add_action('wp_ajax_nopriv_wc_woocommerce_clear_cart_url', 'wc_woocommerce_clear_cart_url');
//added wc_ prefix in case of function name conflict
function wc_woocommerce_clear_cart_url() {
global $woocommerce;
$returned = ['status'=>'error','msg'=>'Your order could not be emptied'];
$woocommerce->cart->empty_cart();
if ( $woocommerce->cart->get_cart_contents_count() == 0 ) {
$returned = ['status'=>'success','msg'=>'Your order has been reset!'];
}
die(json_encode($returned));
}
and the js/ajax side..:
$("#cancelorder").on('click',function(){
if(confirm('Are you sure you want to clear all rows?')){
$.ajax({
type: 'POST',
dataType: 'json',
url: '/wp-admin/admin-ajax.php?action=wc_woocommerce_clear_cart_url',
data: {action : 'wc_woocommerce_clear_cart_url'},
success: function (data) {
if (data.status != 'success') {
alert(data.msg);
} else {
$('#itemrows').html('');
addrows();
}
}
});
} else {
//back out with no action
}
});