So I’m trying to ajaxify a simple POST method add to cart button so that the button doesn’t redirect me to the cart page when it’s pressed. It seems like basically every single question asking this problem has a different solution and I’ve tried a number of them but haven’t found any success yet, so I’m hoping someone can help me out.
This is the code that I’m using to generate the add to cart button:
hello there
To ajaxify the add to cart button in your Shopify store, you can use JavaScript to prevent the default form submission behavior and instead send an AJAX request to add the product to the cart. Here’s an example of how to do this:
- Add an ID to your form element so that you can target it with Javascript:
- In your theme’s JavaScript file, add an event listener to the form’s submit event, prevent the default form submission behavior, and send an AJAX request to add the product to the cart:
$('#add-to-cart-form').on('submit', function(event) {
event.preventDefault(); // prevent default form submission
$.ajax({
type: 'POST',
url: '/cart/add.js',
data: $(this).serialize(),
dataType: 'json',
success: function() {
// Do something on success (e.g. show a success message)
},
error: function() {
// Do something on error (e.g. show an error message)
}
});
});
This code listens for the submit event on the #add-to-cart-form element, and then prevents the default form submission behavior with event.preventDefault(). It then sends an AJAX request to the /cart/add.js URL with the form data using the $.ajax() method from jQuery. On success, you can do something like show a success message, and on error, you can do something like show an error message.
hope this helps
Hello,
This seemed to work! However, my cart drawer only gets updated upon reloading the page. Is there any way to update the cart drawer in real time? For reference, the theme I am using is Broadcast.
Hello,
This seemed to work! However, my cart drawer only gets updated upon reloading the page. Is there any way to update the cart drawer in real time? For reference, the theme I am using is Broadcast.