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
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();
});
WooCommerce AJAX Cart is a WordPress Plugin that changes the default behavior of WooCommerte Cart Page, allowing a buyer to see the Total price calculation when change the Quantity of a product, without need to manually click on “Update cart” button. This improves the user experience when purchasing a product.
Under WooCommerce > Settings > Products > General it's recommended to disable Ajax add to cart behavior and, if possible, to enable redirection to the Cart page. This will always force a page reload (and/or a redirect) and therefore will save the user an Ajax call needed to update the Cart on the go.
Disable Cart Fragmentation Using a Plugin Once you've downloaded and installed the plugin, go to it's settings and scroll down to the Site Performance section. Then check the box next to Disable WooCommerce Cart Fragments and click the Save Changes button at the bottom.
Simply go to the plugins page and search for the plugin you want. Once the plugin has been installed and activated, you need to get to the main settings page to configure the settings how you would like. To do this, click on WooCommerce > Menu Cart Setup.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With