I have implemented Ajax to my "Add to Cart" button so that customers can add products to their cart without reloading the page.
Here is bare minimum of code which I used in order to achieve successful Ajax call in Product Details page for adding Product to Cart without refresh:
<form method="post" action="<?php /* @escapeNotVerified */ echo $block->getSubmitUrl($_product); ?>" id="product_addtocart_form"<?php if ($_product->getOptions()) {echo ' enctype="multipart/form-data"';} ?>>
<input type="hidden" name="product" value="<?php /* @escapeNotVerified */ echo $_product->getId(); ?>" />
<button type="submit">Add to Cart</button>
<script type="text/x-magento-init">
{
"#product_addtocart_form": {
"catalogAddToCart": {
"bindSubmit": true
}
}
}
</script>
</form>
Well, this far everything works perfect. When the button is clicked, message appears in page about successful Product adding to Cart.
The problem is when Product cannot be added to Cart for some reason (for example, out of stock). Then instead of message showing in page dynamically, the refresh happens and only then message pops out in page.
How do I stop refresh in those cases and simply just show the message about reason why Product is not able to be added to Cart?