H
H
hypero2022-02-08 01:48:40
WooCommerce
hypero, 2022-02-08 01:48:40

Ajax cart update?

Hello.
I have a shopping cart in a modal window. It is not possible to do ajax when changing the number of goods.

$(document).on('change', '.qty', function (e)
    {
     e.preventDefault();
     var qty = $(this).val();
     var cart_item_key = $(this).attr("id");

   $.ajax({
        type: 'POST',
        dataType: 'json',
        url: cart_ajax.ajaxurl,
        data: {action : 'update_item_from_cart', 'cart_item_key' : cart_item_key, 'qty' : qty,  },
        success: function (data) {
           alert('Updated successfully.');
        if (data) {
            alert('You missed something');
        }else{
            alert('Updated Successfully!!!');
        }
    }

    });


function update_item_from_cart() {
     $cart_item_key = $_POST['cart_item_key'];   
     $quantity = $_POST['qty'];     

    // Get mini cart
    ob_start();

    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item)
    {
        if( $cart_item_key == $_POST['cart_item_key'] )
        {
            WC()->cart->set_quantity( $cart_item_key, $quantity, $refresh_totals = true );
        }
    }
    WC()->cart->calculate_totals();
    WC()->cart->maybe_set_cart_cookies();
    return true;
}

add_action('wp_ajax_update_item_from_cart', 'update_item_from_cart');
add_action('wp_ajax_nopriv_update_item_from_cart', 'update_item_from_cart');


The code is taken from the Internet, I'm very bad with ajax.
I would really appreciate any help.

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