1
votes

I have found snippet in Github that suppose to work, but as you can see in the comments, it's lacking of cache logic.

I'm trying to update the mini cart on each quantity change using ajax.

Right now I'm lost, can't find anything that works and update my Woocommerce mini cart quantity.

Here is functions.php

//Add mini cart quantity field
add_filter( 'woocommerce_widget_cart_item_quantity', 'add_minicart_quantity_fields', 10, 3 );
function add_minicart_quantity_fields( $html, $cart_item, $cart_item_key ) {
    $product_price = apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $cart_item['data'] ), $cart_item, $cart_item_key );

    return woocommerce_quantity_input( array('input_value' => $cart_item['quantity']), $cart_item['data'], false ) . $product_price;
}


//Update mini cart
function ajax_update_mini_cart() {
  echo wc_get_template( 'cart/mini-cart.php' );
  die();
}
add_filter( 'wp_ajax_nopriv_ajax_update_mini_cart', 'ajax_update_mini_cart' );
add_filter( 'wp_ajax_ajax_update_mini_cart', 'ajax_update_mini_cart' );

and my ajax script

// Update Mini Cart
$(document).ready(function () {
  jQuery('#cart').on('change', 'input', function () {
    $.post(
      woocommerce_params.ajax_url,
      { action: 'mode_theme_update_mini_cart' },
      function (response) {
        $('#mode-mini-cart').html(response);
      }
    );
  });
});

I receive the following console error from javascript:

POST http://localhost/wordpress/wp-admin/admin-ajax.php 400 (Bad Request)

But I don't understand why, I have double checked the script and the function, things should work fine.

How can I refresh Woocommerce minicart based on ajax and prevent cache overriding the refresh?

1

1 Answers

1
votes

All other possibilities aside. At the very least, your action is named incorrectly in the ajax action.

// Update Mini Cart
$(document).ready(function () {
  jQuery('#cart').on('change', 'input', function () {
    $.post(
      woocommerce_params.ajax_url,
      { action: 'ajax_update_mini_cart' }, // This must match the name of your wp_ajax filter
      function (response) {
        $('#mode-mini-cart').html(response);
      }
    );
  });
});

The above is based on these lines:

add_filter( 'wp_ajax_nopriv_ajax_update_mini_cart', 'ajax_update_mini_cart' );
add_filter( 'wp_ajax_ajax_update_mini_cart', 'ajax_update_mini_cart' );

where the wp_ajax_{your_action_name} and wp_ajax_nopriv_{your_action_name} must match the ajax action.

Could there still be an issue with your function? Yes... but this is most likely why you're getting the Error 400