0

I realise there are duplicate threads, but the solutions posed aren't working (100%) - this is the solution I am working with https://stackoverflow.com/a/24027583/1826992. Basically the ajax call is removing the item from the cart but the mini-cart isn't updating until I refresh the page. Here's where I'm at:

add_action( 'wp_footer', 'add_js_to_wp_wcommerce');

function add_js_to_wp_wcommerce(){ ?>
    <script type="text/javascript">
    jQuery('body').on('click',".remove",function (){
        var product_id = jQuery(this).attr("data-product_id");
                console.log(product_id);
        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            url: "/wp-admin/admin-ajax.php",
            data: { action: "product_remove", 
                    product_id: product_id
            },success: function(data){
                console.log(data);
            }
        });

        return false;
    });
    </script>
<?php }



add_action( 'wp_ajax_product_remove', 'product_remove' );
add_action( 'wp_ajax_nopriv_product_remove', 'product_remove' );
function product_remove() {
    $cart = WC()->instance()->cart;
    $id = $_POST['product_id'];
    $cart_id = $cart->generate_cart_id($id);
    $cart_item_id = $cart->find_product_in_cart($cart_id);

    if($cart_item_id){
       $cart->set_quantity($cart_item_id,0);
    }
}

As I mentioned this all seems to work up until "action". Console.log(data) at this point only carries "0". I assume this should have product_id.

Thanks in advance for any help.

Community
  • 1
  • 1
epluribusunum
  • 125
  • 2
  • 15

1 Answers1

1

Return something from your php function & use wp_die() after the return,and wrap your js in document ready statement

madalinivascu
  • 32,064
  • 4
  • 39
  • 55
  • I've implemented those changes. Any recommendations on what to return? I've returned $cart but no cart still isn't refreshing until I reload the page. Thanks. – epluribusunum Sep 21 '16 at 11:20
  • you need to return the updated cart, or just a message that the cart was updated , based on that you update the cart list on the page – madalinivascu Sep 21 '16 at 11:21
  • do you know how to update the cart list? Sorry, I am struggling a bit with this. Thanks in advance. – epluribusunum Sep 27 '16 at 17:12
  • @epluribusunum return the added element from the ajax and build the list item with html after that append it to your current list – madalinivascu Sep 28 '16 at 03:49