Ad

Ajaxify Link So That It Still Accesses Address On Click But Doesn't Change Page

I've got a link that removes an item from a cart, except that when you click that link it redirects you to the cart with the item now removed. Is it possible to make it so that you can still click it and it still does its thing but it doesn' change the page (i.e. it doesn't send the user to the cart)?

Note: I'm working with Liquid on Shopify

Link:

<a target="_blank" rel="nofollow noreferrer" href="/cart/change?line={{ forloop.index }}&amp;quantity=0" class="cart__remove">
                <small>{{ 'cart.general.remove' | t }}</small>
</a>

Ad

Answer

Since you have jQuery included try adding the following script

jQuery(function($){
  $(document).on('click', 'a.cart__remove', function(e){
     e.preventDefault();
     var url = this.href;
     $.get(url, function(html){
       // here you know that the page the link was pointing to has executed
       // you might need to reload your card or parse it from the html you get here
       // because the index of the cart items has changed after removing one of them
       // and because you also need to update your shown cart to hide/remove the item that was selected

     });
  });
});
Ad
source: stackoverflow.com
Ad