Woocommerce |由Ajax清除购物车

时间:2016-10-21 10:59:22

标签: javascript php ajax wordpress woocommerce

我正在尝试设置一个AJAX功能来清除我的购物车

HTML

<a onclick="clearCart(this)" data-href="/product-page/" data-productID="182">Go to Product</a>

的JavaScript

function clearCart(d) {
    jQuery(document).ready(function($) {
        var productID = d.getAttribute("data-productID");
        $.ajax({
            url: "addtocart.php",
            data: {productID: productID},
            type: "post",
            success: function(output) {
                window.location = d.getAttribute("data-href");
                //alert(output);
            }
        });
    });
}

PHP

if(isset($_POST['productID']) && !empty($_POST['productID'])) {   
    global $woocommerce;
    $woocommerce->cart->empty_cart();
    //echo $_POST['productID'];
}

结果

  • 由第3个PHP行引起的内部服务器错误
  • 警报var输出正在运行(检查已注释的代码)

我自己想出了@MirzaP的一些很好的帮助

JS

      function clearCart(d) {
            jQuery.post(
                "https://dercampus.ch/wp-admin/admin-ajax.php", 
                //ajaxurl, 
                {
                    "action": "clearcart",
                    "data":   d.getAttribute("data-productid")
                }, 
                function(){
                    window.location = d.getAttribute("data-href");
                }
            );
        }

PHP

add_action('wp_ajax_nopriv_clearcart',function(){
    global $woocommerce;
    $woocommerce->cart->empty_cart();
});

2 个答案:

答案 0 :(得分:2)

请将您的PHP代码更改为

  setFilterActive(type, min, max) {
    const filterObj = {
      type: type,
      min: min,
      max: max
    };
    let queryObject = this.state.queryObject;
    _.reject(queryObject.query.filters, filter => filterObj.isEqual(filter));
    let newQueryObject = _.merge(filterObj,queryObject.query.filters);
    console.log(filterObj);
    this.setState({queryObject:newQueryObject});
    console.log("Filters Array:" , this.state.queryObject.filters);
  }

传入的参数是数据而不是productID

答案 1 :(得分:0)

// before addto cart, only allow 1 item in a cart
add_filter( 'woocommerce_add_to_cart_validation', 'woo_custom_add_to_cart_before' );
 
function woo_custom_add_to_cart_before( $cart_item_data ) {
 
    global $woocommerce;
    $woocommerce->cart->empty_cart();
 
    // Do nothing with the data and return
    return true;
}