Skip to content

Instantly share code, notes, and snippets.

@helpercode0
Created August 12, 2024 17:53
Show Gist options
  • Save helpercode0/2669585fbf28c15a811c6ef63dc5d41e to your computer and use it in GitHub Desktop.
Save helpercode0/2669585fbf28c15a811c6ef63dc5d41e to your computer and use it in GitHub Desktop.
Clear Cart on Page Load Shopify
<script>
/**
* Clears the cart in Shopify and logs the result or errors.
*/
function clearCart() {
fetch('/cart/clear.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(response => response.json())
.then(data => {
console.log('Cart cleared:', data);
// Optionally, you can call another function to update the UI or inform the user
updateCartUI();
})
.catch(error => {
console.error('Error clearing cart:', error);
// Optionally, you can call another function to handle the error
handleCartError(error);
});
}
/**
* Updates the cart UI after clearing the cart.
*/
function updateCartUI() {
// Implementation to update the cart UI, e.g., refresh cart contents or display a message
console.log('Cart UI updated.');
}
/**
* Handles errors that occur during the cart clearing process.
* @param {Error} error - The error object
*/
function handleCartError(error) {
// Implementation to handle errors, e.g., display an error message to the user
console.error('Handling cart error:', error);
}
// Example usage: Clear the cart when the DOM content is loaded
document.addEventListener('DOMContentLoaded', () => {
clearCart();
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment