Add variable product to cart with Ajax in woocommerce
<p>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.</p>

<pre><code>element.on('click', 'button[type="submit"]', event =&gt; {
    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 += `&amp;attribute_pa_${attr.slug}=${attr.option}`;
                }
                xWWWFormUrlencodedData += `&amp;add-to-cart=${scope.singleCopy.id}`;
                xWWWFormUrlencodedData += `&amp;product_id=${scope.singleCopy.id}`;
                xWWWFormUrlencodedData += `&amp;variation_id=${scope.selectedVariation.id}`;
            }
            break;
        }
        case 'simple': {
            xWWWFormUrlencodedData += `&amp;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 =&gt; {
        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 =&gt; {
        console.error(data);
        // TODO: handle error
    });

});
</code></pre>

<p>If I do not send the <code>product_id</code>, 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.”</p>

<p>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?</p>