My code below works except that it not only adds the variable product with the selected variation to the cart, but it additionally adds the same quantity of the same product with no variation as if it was a simple product.
element.on('click', 'button[type="submit"]', event => {
event.preventDefault();
const quantity = parseInt(element.find('input[name="quantity"]').val(), 10) || 1;
const addToCartUrl = '/shopping-basket/?wc-ajax=add_to_cart';
let xWWWFormUrlencodedData = `quantity=${quantity}`;
switch (scope.singleCopy.type) {
case 'variable': {
if (scope.selectedVariation) {
for (const attr of scope.selectedVariation.attributes) {
xWWWFormUrlencodedData += `&attribute_pa_${attr.slug}=${attr.option}`;
}
xWWWFormUrlencodedData += `&add-to-cart=${scope.singleCopy.id}`;
xWWWFormUrlencodedData += `&product_id=${scope.singleCopy.id}`;
xWWWFormUrlencodedData += `&variation_id=${scope.selectedVariation.id}`;
}
break;
}
case 'simple': {
xWWWFormUrlencodedData += `&product_id=${scope.singleCopy.id}`;
break;
}
default: {
console.error(`Unknown product type ${scope.singleCopy.type}.`); //eslint-disable-line no-console
}
}
$http.post(addToCartUrl, xWWWFormUrlencodedData, {
withCredentials: true,
headers: {
'Cache-Control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
Pragma: 'no-cache'
}
}).success(result => {
if (result.error) {
console.warn('The product has been added to the cart despite that the result object indicates an error!');
// TODO: handle error
return;
}
console.log('Success.', result);
$rootScope.$broadcast('/cart/update/add');
}).catch(data => {
console.error(data);
// TODO: handle error
});
});
If I do not send the product_id
, only the variable product with the selected variation is added to the cart (great!), BUT the result object indicates an error (with no description). If I then navigate to the cart page I get another error message in the ui: “Sorry, this product cannot be purchased.”
I think I have tried all permutations by now, setting the variation id instead of the product id on the parameters, removing and adding back parameters and so on. Any idea how to solve this?