简体   繁体   中英

Shopify, Liquid, Alpine JS, Ajax can't redirect to cart after firing addToCart

Can't figure out why after my ajax addToCart function is called not being redirected to cart?

The product is getting into cart as expected.

I have tried preventingDefault and not preventing.

Here is what response and formData look like in image below.

在此处输入图像描述

Here is my product form.

      <div class="tw-p-8">
          <h2 class="tw-mb-4 tw-text-white">Your Selections</h2>
          {% assign product_form_id = 'product-form-' | append: section.id %}
          {%- form 'product',
            product,
            id: product_form_id,
            class: 'form',
            novalidate: 'novalidate',
            data-type: 'add-to-cart-form'
          -%}
            <input
              type="hidden"
              name="id"
              value="{{ product.selected_or_first_available_variant.id }}"
              disabled
            >
            <div class="product-form__buttons">
              <button
                type="submit"
                @click.prevent="addToCart(items, box_size)"
                :class="full_box ? 'tw-bg-ctaColor' : ''"
                class="tw-bg-white tw-text-brandText tw-flex tw-justify-center tw-py-4 tw-px-6 tw-rounded-full tw-font-bold"
              >
                <p class="" x-show="!full_box">
                  <span x-text="items_selected" class="tw-mr-2"></span><span class="tw-mr-2">of</span
                  ><span class="tw-font-bold" x-text="box_size"></span><span class="tw-ml-2">Selected</span>
                </p>
                <p x-show="full_box" class="">Add to cart</p>
              </button>
            </div>
          {%- endform -%}
        </div>

Here is my addToCart function.

    <div
        x-data="
          {
            addToCart(items, size){
             const price = getBoxPrice(size)
             console.log({price})
             let itemsToAdd = items.map((item) => {
               return item['title'];
             })

             let selectedItems = itemsToAdd.toString()
             console.log({selectedItems})
             console.log({itemsToAdd})
              let formData = {
              'items': [{
                'id': 44202123100470,
                'quantity': 1,
                'properties': {
                  'Box Items': selectedItems,
                  }
                }]
              };
              console.log({formData})
              fetch(window.Shopify.routes.root + 'cart/add.js', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
              })
              .then(response => {
                console.log(response)
                return response.json();
              })
              .then((data) => {
                console.log('Success:', data);
              })
              .catch((error) => {
                console.error('Error:', error);
              });
              reset()
            }
          }
        "
        class="tw-mt-12 tw-flex tw-flex-col tw-p-auto tw-bg-brandText tw-opacity-80"
      > ....</div>

The way I solved this was to use the Location API add location.href="/cart" in the success promise of the Ajax call.

             fetch(window.Shopify.routes.root + 'cart/add.js', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
              })
              .then(response => {
                console.log(response)
                return response.json();
              })
              .then((data) => {
               location.href = '/cart';
                console.log('Success:', data);
              })
              .catch((error) => {
                console.error('Error:', error);
              });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM