'Add add-to-cart button in Shopify Collections
I have a problem with the ENVY template. This template does not have support for adding a shopping cart button in the collections that are located in the home. before this I have decided to add my own code in the area where these products are shown, but when pressing the button add to cart, it sends me to an error page with the message "Parameter Missing or Invalid: Required parameter missing or invalid: items" my codes are as follows:
function instantBuy(){
var $ = jQuery;
var formParams = $('form.cart').serialize();
$.ajax({
url: "/cart/add",
type: "post",
data: formParams,
success: function(){
window.location.href = "/checkout";
},
error: function(){
}
})
}
form code
<form action="/cart/add" method="post" class="variants" id="product-actions-{{ product.id }}" enctype="multipart/form-data">
<input type="hidden" name="variantId" value="{{ product.variants[0].id }}" />
<button class="button buynow-btn" title="Buy" onClick="instantBuy()"><span>Buy now</span></button>
</form>
Solution 1:[1]
When you send a request to the /cart/add has to be sent "id" arguments. At the moment you are sending "variantId" instead of "id".
Also in your JavaScript there is no preventDefault to preserver the browser to send the request.
In another hand, this can be done without JavaScript.
Here is the updated code:
<form action="/cart/add" method="post" class="variants" id="product-actions-{{ liquidObject.id }}" enctype="multipart/form-data">
<input type="hidden" name="id" value="{{ liquidObject.variants[0].id }}" />
<input type="hidden" name="return_to" value="/checkout" />
<button class="button buynow-btn" title="Buy"><span>Buy now</span></button>
</form>
Also added a "return_to" hidden field, which will redirect the user directly to checkout when hits the button
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |