"Add to Cart" button use AJAX

Acilo
New Member
15 0 0

hello,
I created a page by APP shogun:
https://maoup.myshopify.com/pages/addtocarttestpage
this APP can add "Add to Cart" button,
but it can't update information until I refresh this page.

my site use AJAX "ADD TO CART",
but when I tried to add "add to cart" code in this page,
unfortunately, it go to cart page directly (not use AJAX "ADD TO CART" )

how could I use AJAX "ADD TO CART" in some page I created like this?
https://maoup.myshopify.com/pages/addtocarttestpage
I want when I clicked "Add to Cart" button,
it can update information directly.

thank you!

0 Likes
Daniel-Anverso
Tourist
8 0 3

Hi, same problem with me. But I fixed using this tutorial: https://support.rechargepayments.com/hc/en-us/articles/360008683774-Adding-an-item-to-the-cart-with-....

I use Prestige theme and paste this code on the 'custom.js' file

$('#add-to-cart-button').click(function(){    
    addItemToCart( ID NUMBER, 1, "1", "Months").    // paste your id product number
  });

  function addItemToCart(variant_id, qty, frequency, unit_type) {
    data = {
      "id": variant_id,
      "quantity": qty
    }
    
    jQuery.ajax({
      type: 'POST',
      url: '/cart/add.js',
      data: data,
      dataType: 'json',
      success: function() { 
        document.documentElement.dispatchEvent(new CustomEvent('cart:refresh', {
          bubbles: true  //this code is for prestige theme, is to refresh the cart
       }));
      }
    });
    document.documentElement.dispatchEvent(new CustomEvent('cart:refresh', {
    	bubbles: true    // same code for prestige theme   
 	 }));
  }

 

you can activate the button with this :

<a id="add-to-cart-button">Add to Ajax Cart </a>

 

SS786
New Member
1 0 0

Can You Please Suggest Me How To Implement This Code To Debutify or Any Other Theme. Or You Could Help In Explaining The Code.

Thank YOu

0 Likes
Daniel-Anverso
Tourist
8 0 3

Ok, I don't know if it works in all themes, but let's try it. 

First, go to Edit code / Assets folder / create a new file called "custom.js" 
In that new file paste the javascript that I added on the previous post. 

Now, go to Layout folder, select Theme.liquid. Search this tag </head> and before that line of code paste this:
<script src="{{ 'custom.js' | asset_url }}" defer></script> 

The final step is to create a new link or button on your page. In my case, I added a link inside a snippet file, it was only this code:

<a id="add-to-cart-button">Add to cart</a>


Hope this works! 

0 Likes
CannaAxella
New Member
2 0 0

I have the same problem using Prestige theme. The problem is caused by the drawer cart that I prefer. I got as far as the shippets. Could you show me how or where to add the links in order for it to work?

 

 

0 Likes
albahg
New Member
1 0 0

Hello, I would like to know how I can open the cart sidebar after deploying this code

0 Likes