L
L
ligisayan2019-01-18 15:01:49
WooCommerce
ligisayan, 2019-01-18 15:01:49

Why does ajax continue to work with the previous object when changing the product?

Hello!
There is a woocommerce store . On the site page, each time I click the id="change" button, I replace one product with another and vice versa, which I set, as in the code below or through a shortcode.

When adding a product to the cart, a modal window pops up with the product, which signals that it has been added.

<?php echo do_shortcode( '[add_to_cart id="21"]' ); ?>


<div id="order-wrapper"><a href="shop/?add-to-cart=21" data-quantity="1" class="btn btn-primary product_type_simple add_to_cart_button ajax_add_to_cart order" data-product_id="21" aria-label="Добавить в корзину" rel="nofollow">Заказать</a></div>
<button id="change">Изменить</button>

$('.add_to_cart_button').on('click', function() {
  $('#modal-cart').modal('show');
});
$('#change').on('click', function() {
  var attr = $('.order').attr("data-product_id");
  if (attr == "21") {
    $('.order').attr("href", "shop/?add-to-cart=42");
    $('.order').attr("data-product_id", "42");
    //$( "#order-wrapper" ).empty();
    //$( "#order-wrapper" ).append('<a href="shop/?add-to-cart=42" data-quantity="1" class="bt btn-primanry product_type_simple add_to_cart_button ajax_add_to_cart order" data-product_id="42" aria-label="Добавить в корзину" rel="nofollow">Заказать</a>' );
  } else {
    $('.order').attr("href", "shop/?add-to-cart=21");
    $('.order').attr("data-product_id", "21");
    //$( "#order-wrapper" ).empty();
    //$( "#order-wrapper" ).append('<a href="shop/?add-to-cart=21" data-quantity="1" class="bt btn-primanry product_type_simple add_to_cart_button ajax_add_to_cart order" data-product_id="21" aria-label="Добавить в корзину" rel="nofollow">Заказать</a>' );
  }
});


Products change, everything is fine, but there is a problem with ajax .

If you add the first item to the cart, click on the change button and add another one (as the contents of the id button and the link have already changed), then the cart will contain 2 pieces of the first item, and not the first and second.

If you refresh the page after changing the product, then the products will be added different, as it should be, so the problem is with ajax - it works with the first copy until reload.

If you control the order buttons with the empty() and append() functionsas I showed in the comments in the code above, ajax already works with different instances of the object and adds different products to the cart, as expected, but the modal window stops popping up, because initially there were no new objects in the DOM..

How to resolve the issue?

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