shopify - when i click on add to cart button, page refreshes and then product is added how can i do this without getting the page refreshing
Solution:
To add an add-to-cart button to a Shopify product page without causing a page refresh, you can use Shopify's AJAX API to perform an AJAX request to the Shopify cart API. This allows you to add products to the cart without a page refresh.
Here's an example code snippet that you can use to achieve this:
- In your product.liquid file, add a button to trigger the AJAX request when clicked:
<div class="buy-now-bx">
{% if card_product.available %}
<form method="post" action="/cart/add" id="add-to-cart-form">
<input type="hidden" name="id" value="{{ card_product.selected_or_first_available_variant.id }}">
<div style="display: flex">
<input type="hidden" name="return_to" value="back" />
<button type="submit" class="button buynow-btn" data-id="{{ card_product.variants.first.id }}" id="add-to-cart-btn">Add to Cart</button>
</div>
</form>
{% else %}
<a class="button buynow-btn" tabindex="0" href="{{ card_product.url | default: '#' }}">Sold out</a>
{% endif %}
</div>
- Add the following code to your theme.js file or create a new file with the following code:
$(document).ready(function() {
$('#add-to-cart-form').submit(function(event) {
event.preventDefault(); // prevent the default form submit behavior
var form = $(this);
var addToCartButton = form.find('#add-to-cart-btn');
var originalButtonText = addToCartButton.text();
addToCartButton.attr('disabled', true).text('Adding...'); // disable the button and change the text
$.ajax({
type: 'POST',
url: '/cart/add.js',
data: form.serialize(),
dataType: 'json',
success: function() {
addToCartButton.text('Added!'); // change the button text
setTimeout(function() {
addToCartButton.attr('disabled', false).text(originalButtonText); // re-enable the button and change the text back to the original text after a delay
}, 1000);
},
error: function() {
addToCartButton.text('Error'); // handle the error by changing the button text
}
});
});
});
This code will handle the form submit event and send an AJAX request to the Shopify cart API when the add-to-cart button is clicked. It will also disable the button and change the text to indicate that the product is being added to the cart. Once the request is complete, it will change the button text to "Added!" and then change it back to the original text after a delay.
Source
Didn't find the answer?
Our community is visited by hundreds of Shopify development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.