Woocommerce “Add to cart” not working by Ajax

I’am working in a theme which uses a custom function to add an item to cart in the shop products page. The function add an element and returns me the current number of items added to the cart.

The function:

Read More
add_action('wp_ajax_nopriv_add_to_cart_item', 'add_to_cart_item');
add_action('wp_ajax_add_to_cart_item', 'add_to_cart_item');
function add_to_cart_item() {
    global $woocommerce;
    $prod_id = intval($_POST['prod_id']);
    $variations=array();
    $woocommerce->cart->add_to_cart( $prod_id , 1 , 0 , $variations );
    echo $woocommerce->cart->get_cart_subtotal();
    die();
}

This function works perfectly fine when I am logged in, however when I’m not it returns me ‘1’ and doesn’t add nothing to cart.

If I go to the product page and press the Add to cart button which has not an Ajax function (is a submit button) it start to works perfectly fine and leaves me add to cart if I come back to the ‘Shop products page’.

Seems like Woocommerce needs to initialize something.

Any idea?
Thanks so much!

EDIT: Solved!

I load the product grid items by Ajax and I bind the events after they are loaded. I called the function with this code:

$('.grid-products .add_to_cart_button').on("click",function(e){
                        if($(this).hasClass('product_type_variable')){
                            return;
                        }
                        e.preventDefault();
                        var data = { 'action': 'add_to_cart_item', 'prod_id': $(this).data('product_id') };

                        $.post(base_url_theme +'/wp-admin/admin-ajax.php', data, 
                        function(resp) {
                            if ($('.menu-buttons .cart').hasClass('hide')) {
                                $('.menu-buttons .cart').removeClass('hide');
                            };
                            $('.menu-buttons .cart .num-items').text(resp);
                        });
 });

But for any reason if I wasn’t logged it doesn’t work.
I am not sure why it wasn’t working but I have solve it assigning to the product buttons the code of: woocommerce/assets/frontend/js/add-to-cart.js instead the js code above.
Perhaps the fragments or the cart_hash are needed when I am not is no logged in.

Thanks!

Related posts