Woocommerce | Clear cart by Ajax

I'm trying to set up an AJAX function to clear my cart

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'];
}

Result

  • Internal Server Error caused by 3rd PHP line
  • Alerting var output is working (check outcommented code)

SOLUTION

I figured it out by myself and some great help from @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();
});

Answers:

Answer

Please change your php code to

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

Your parameter that is passed in is data and not productID

Answer

// 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;
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.