[Vuejs]-Adding multiple products to WooCommerce Cart โ€“ AJAX

0๐Ÿ‘

Ok so after inspecting the network tab this is the solution that works:

this.toBeAdded.forEach((item, i) => {
          let adder = new FormData();

          adder.append('attribute_alege-zona', Object.values(item.attributes)[0]);
          adder.append('attribute_tratament', Object.values(item.attributes)[1]);
          adder.append('quantity', 1);
          adder.append('product_id', item.variation_id);
          adder.append('variation_id', item.variation_id);

          console.log(adder);

          let me = this;

          let send = setTimeout(function() {
            axios({
              method: "post",
              url: "https://HOST/?wc-ajax=add_to_cart",
              data: adder,
              headers: { "Content-Type": "multipart/form-data" },
              withCredentials: true,
            })
            .then(function (response) {
                if(i == 0) {
                  document.cookie = document.cookie + " woocommerce_items_in_cart=1; path=/";
                }else if (i==me.toBeAdded.length-1){
                  window.location.href = "https://HOST/cart";
                }
            })
            .catch(function (response) {
              console.log(response);
            });
          }, i*500);
       });

Basically if it is the fist product I am adding the WC items in cart cookie.
If it is the last product I redirect to cart.

Each call is delayed by i*500, where i is the index of the array of products

Leave a comment