Mikey Musch
Mikey Musch

Reputation: 609

Error Updating Cart Item Quantity Using AJAX - WooCommerce

I am trying to update the quantity of an item in my WooCommerce cart using AJAX. When the cart is updated I'd like the total prices to reflect the new prices. I am basically copying from WooCommerce - auto update total price when quantity changed but have changed a few things.

There are also a few things in their code I don't understand like "rf_cart_params" - It seems like that variable is defined somewhere outside of what they've provided.

In my functions.php I have

function enqueue_cart_qty_ajax() {

    wp_register_script( 'cart-qty-ajax-js', get_template_directory_uri() . '/js/cart-qty-ajax.js', array( 'jquery' ), '', true );
    wp_localize_script( 'cart-qty-ajax-js', 'cart_qty_ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
    wp_enqueue_script( 'cart-qty-ajax-js' );

}
add_action('wp_enqueue_scripts', 'enqueue_cart_qty_ajax');

function ajax_qty_cart() {
    check_ajax_referer( 'ajax_qty_cart', 'security' );

    // Skip product if no updated quantity was posted or no hash on WC_Cart
    if( !isset( $_POST['hash'] ) || !isset( $_POST['quantity'] ) ){
        exit;
    }

    $cart_item_key = $_POST['hash'];

    if( !isset( WC()->cart->get_cart()[ $cart_item_key ] ) ){
        exit;
    }

    $values = WC()->cart->get_cart()[ $cart_item_key ];

    $_product = $values['data'];

    // Sanitize
    $quantity = apply_filters( 'woocommerce_stock_amount_cart_item', apply_filters( 'woocommerce_stock_amount', preg_replace( "/[^0-9\.]/", '', filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT)) ), $cart_item_key );

    if ( '' === $quantity || $quantity == $values['quantity'] )
        exit;

    // Update cart validation
    $passed_validation  = apply_filters( 'woocommerce_update_cart_validation', true, $cart_item_key, $values, $quantity );

    // is_sold_individually
    if ( $_product->is_sold_individually() && $quantity > 1 ) {
        wc_add_notice( sprintf( __( 'You can only have 1 %s in your cart.', 'woocommerce' ), $_product->get_title() ), 'error' );
        $passed_validation = false;
    }

    if ( $passed_validation ) {
        WC()->cart->set_quantity( $cart_item_key, $quantity, false );
    }

    // Recalc our totals
    WC()->cart->calculate_totals();
    woocommerce_cart_totals();
    exit;
}

add_action('wp_ajax_qty_cart', 'ajax_qty_cart');
add_action('wp_ajax_nopriv_qty_cart', 'ajax_qty_cart');

And in cart-qty-ajax.js I have

jQuery( function( $ ) {

    // wc_cart_params is required to continue, ensure the object exists
    if ( typeof wc_cart_params === 'undefined' ) {
        return false;
    }

    $( document ).on( 'change', '.quantity, input[type=number]', function() {
        var qty = $( this ).val();
        var currentVal  = parseFloat( qty);

        //$( 'div.cart_totals' ).block({ message: null, overlayCSS: { background: '#fff url(' + wc_cart_params.ajax_loader_url + ') no-repeat center', backgroundSize: '16px 16px', opacity: 0.6 } });

        var item_hash = $( this ).attr( 'name' ).replace(/cart\[([\w]+)\]\[qty\]/g, "$1");
        var data = {
            action: 'qty_cart',
            security: cart_qty_ajax.ajax_qty_cart_nonce,
            quantity: currentVal,
            hash : item_hash 
        };

        $.post( cart_qty_ajax.ajax_url, data, function( response ) {

            console.log( data );
            $( 'div.cart_totals' ).replaceWith( response );
            $( 'body' ).trigger( 'qty_cart' );

        });
        return false;      

    });
});

The HTML for the quantity button is as follows:

<td class="product-quantity">
    <div class="quantity">
        <input type="number" step="1" min="0"
         name="cart[2bcc28b6c27e9885a4735544844c57fc][qty]"
         value="4" title="Qty" class="input-text qty text" size="4">
    </div>
</td>

When I console.log the data I get

Object {action: "qty_cart", security: undefined, quantity: 4, hash: "2bcc28b6c27e9885a4735544844c57fc"}

When I change the quantity of the item the response that is outputted is just "-1"

Any Ideas where I'm going wrong?
Thank you in advance!

Upvotes: 2

Views: 3217

Answers (1)

You have a problem with this line of code

check_ajax_referer( 'ajax_qty_cart', 'security' );

I don't know what is exactly wrong (trying to figure this our for myself ATM), but if you will comment this line - you'll get your correct output.

Upvotes: 0

Related Questions