[英]Remove all cart items from a button on a custom page using AJAX
我正在構建一個批量訂單表單插件(用於wordpress / woocommerce)-所有添加到購物車的功能都運行良好。 我正在努力創建“取消訂單”按鈕,按下該按鈕可以清除所有項目行(此位有效)以及從購物車中刪除所有項目。
我正在嘗試結合使用AJAX / js,php和標准HTML ..:
我的按鈕..:
<button class="btn btn-danger btn-lg" id="cancelorder">Cancel Order</button>
我的購物車清空功能..:
add_action( 'init', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
global $woocommerce;
if ( isset( $_GET['empty-cart'] ) ) {
$woocommerce->cart->empty_cart();
}
}
最后,我的js函數/ ajax調用..:
$("#cancelorder").click(function(){
if(confirm('Are you sure you want to clear all rows?')){
$(".addedrow").remove(); //removes line items - not related to issue
$.ajax({
type: "POST",
url: '/wp-admin/admin-ajax.php?action=woocommerce_clear_cart_url',
data: {action : 'woocommerce_clear_cart_url'},
success: function (res) {
if (res) {
alert('Removed Successfully');
}
}
});
} else {
//back out with no action
}
});
行從窗體中刪除,但項目保留在購物車中。
好吧,看來您正在發送POST請求
type: "POST"
並嘗試恢復控制器上的GET參數
if ( isset( $_GET['empty-cart'] ) )
另外,您正在尋找的鍵( 'empty-cart'
)似乎根本不存在...至少在您提供的這段代碼中...
更新:通過將上面的現有代碼修改為以下內容,我能夠使它正常工作:
空車功能..:
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));
}
和js / ajax方面..:
$("#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
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.