S
S
sergo5732021-11-23 16:58:08
AJAX
sergo573, 2021-11-23 16:58:08

How to make an AJAX empty cart button on woocommerce?

Hello, I'm trying to make an AJAX button to completely empty the cart, without reloading the page, this is what I have:
In function.php:

function woocommerce_clear_cart_url() {
  global $woocommerce;
  if( isset($_REQUEST['empty']) ) {
    $woocommerce->cart->empty_cart();
  }
}
add_action( 'init', 'woocommerce_clear_cart_url' );
function my_custom_function(){
 global $woocommerce;
$woocommerce->cart->empty_cart();
}
add_action('wp_ajax_empty', 'my_custom_function');
add_action('wp_ajax_nopriv_empty', 'my_custom_function');


On the cart page:
<script>
jQuery(function($){
 $('#btnclear').click(function(){

 $.ajax({
        url: '/wp-admin/admin-ajax.php',    
        type: "POST",
        cache: false,
        data: {action: 'empty'} //action defines which function to use in add_action
});
});
});
</script>
<button name="empty" id="btnclear">Очистить корзину</button>


When you click on the button, nothing happens, but when you reload the page, all the goods from the basket disappear... Tell me, what's wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question