S
S
Sergey Konstantinov2019-09-29 01:37:17
WooCommerce
Sergey Konstantinov, 2019-09-29 01:37:17

Why are not all items added to the cart?

$(".tocart").on( "click", function() {
var cart_date = $('.sbor .tocart').attr("data-cart").split(';');
cart_date.forEach(function(item, i, cart_date) {
  product = item.split(',');
  varid=product[2];
  qty=product[1];
var data = {
    action: 'my_action',
        product_id: product[0],
        qty : qty,
    variable_id: varid ,
    };
    jQuery.post( myajax.url, data, function(response) {
    });
});
});

add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
function my_action_callback() {
   $product_id= intval( $_POST['product_id'] );
   $qty= intval( $_POST['qty'] );
   $variable_id= intval( $_POST['variable_id'] );
   global $woocommerce;
   $woocommerce->cart->add_to_cart($product_id, $qty, $variable_id);
   wp_die(); 
}

Here is the main code responsible for ajax adding items to the cart, everything works well for 1 item, that is, everything is added well in one addition.
and when there are already several goods and the forEach loop is triggered, then the goods disappear, out of 5, let's say 2 are added, in random order. from woocommerce doesn't seem to notice
Yes, I need to add several products at once.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pychev Anatoly, 2019-09-29
@pton

Woocommerce makes checks before adding to the cart and in case of an error it fills in the notification. Then he displays these messages to the user.
Your code is ignoring this.
Check the messages, maybe they have the answer.
Look at the native add-to-cart code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question