简体   繁体   中英

Shopify AJAX Request - e.preventDefault Not Working

I have a cart popup that shows the contents of the cart using an AJAX request. Inside this popup, I have an "X" link meant to remove that line item from the cart. However, when I use the following code,

$('#remove-from-cart').click(function(e) {  
      var link = $(this).attr('href');
      // Preven link normal behavior
      e.preventDefault();   
      $.ajax({
        url: link,
        type:'GET',
        success: function(data){
          $('#receipt-wrapper .receipt-row-2').html($(data).find('.line-item-container').html());
        }
      });
  });

the normal link behavior of the X link still happens, meaning it takes you to the updated cart page immediately.

HTML of "remove link"

<div class="grid__item receipt--hide small--one-sixth medium--one-sixth large--one-twelfth xlarge--one-twelfth icon-remove">
    <p class="cart__product-meta">
         <a href="/cart/change?line={{ forloop.index }}&amp;quantity=0" id="remove-from-cart">
            {% include 'svg-icon-remove' %}
         </a>
    </p>
</div>

What am I doing wrong? (I'm using an identical block of JS code to make the popup appear and it works for that)

Thanks!

Remove href from anchor tag and use in in the click function.,

Take a data attribute and add the required url in the data attribute.

<div class="grid__item receipt--hide small--one-sixth medium--one-sixth large--one-twelfth xlarge--one-twelfth icon-remove">
    <p class="cart__product-meta">
         <a id="remove-from-cart" data-url="/cart/change?line={{ forloop.index }}&amp;quantity=0">
            {% include 'svg-icon-remove' %}
         </a>
    </p>
</div>

Now, refer the data attribute using this in the function.

$('#remove-from-cart').click(function(e) {  
      var link = this.data("url")
      // Preven link normal behavior
      e.preventDefault();   
      $.ajax({
        url: link,
        type:'GET',
        success: function(data){
          $('#receipt-wrapper .receipt-row-2').html($(data).find('.line-item-container').html());
        }
      });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM