admin管理员组

文章数量:1289911

Here is the button's code:

    {% assign p_annual = all_products[section.settings.paid_product_annual] %}
    {% assign p_free = all_products[section.settings.free_product] %}

        {% if section.settings.productlink1label != blank %}
            <button class="btn"
                 type="submit" 
                 name="paid-plan" 
                 id="paid-plan-option-annual" 
                 data-variant-id="{{ p_annual.selected_or_first_available_variant.metafields.subscriptions.discount_variant_id }}" 
                 data-variant-interval-value="{{ p_annual.metafields.subscriptions.shipping_interval_frequency }}" 
                 data-variant-interval-unit="{{ p_annual.metafields.subscriptions.shipping_interval_unit_type }}"
                 data-quickadd-id="{{ p_annual.selected_or_first_available_variant.id }}"
                 data-quickadd-properties
             >
                        {{ p_annual.selected_or_first_available_variant.price | money_without_trailing_zeros }}{{ section.settings.productlink1label }}
             </button>
        {% endif %}

The code grabs the item by the ID and makes an AJAX request.

// quick add
    _document.on('click', '[data-quickadd-id]', function() {
        let _this = $(this);

        loadingBarTrigger('start');

        itemAdd(
            _this.attr('data-quickadd-id'), 
            _this.attr('data-quickadd-properties'), 
            (_this.attr('data-quickadd-quantity'))
                ? _this.attr('data-quickadd-quantity')
                : 1, 
            (!html.is('#cart')) ? true : false,
            (html.is('#cart')) ? true : false
        );
    });

inside of cart function:

onst itemAdd = (variantId, properties, qty, openCart, reloadPage) => {
        $.ajax({
            type: 'POST',
            dataType: 'html',
            url: `/cart/add.js`,
            data: 
                {
                    id: variantId,
                    quantity: qty,
                    properties: (properties) 
                        ? JSON.parse(properties) : null
                },
                
            error: function(data) {
                console.error(data);

                loadingBarTrigger('done');
            },
            success: function() {
                loadingBarTrigger('move');

                $.ajax({
                    url: '/cart',
                    dataType: 'html',
                    error: function(data) {
                        console.error(data);

                        loadingBarTrigger('done');
                    },
                    success: function(data) {
                        let minicartContent = $('#minicart-content');
                        let cartItemsHtml = $(data).find('#cart-content #cart-items').html();

                        // insert or prepend cart HTML
                        (minicartContent.find('#cart-items').length)
                            ? minicartContent.find('#cart-items').html(cartItemsHtml)
                            : minicartContent.prepend(cartItemsHtml);

                        // remove giftbox content if exists
                        (minicartContent.find('#cart-giftbox .item-info').length)
                            ? minicartContent.find('#cart-giftbox .item-info').remove()
                            : '';

                        loadingBarTrigger('done');
                        cartTotalUpdate();

                        // open cart
                        (openCart && !html.is('#cart'))
                            ? minicartTrigger.trigger('click') : '';

                        (reloadPage)
                            ? location.reload() : '';
                    }
                });
            }
        });
    }

I know this is possible with the AJAX API update last year. But I'm unsure how to implement it in my store. The data-variant-id only accepts one value if I'm not mistaken. And what's data-variant-id es first gets precedence. I guess the main thing is that I'm unsure how to send json with the submit button.

Any ideas?

Here is the button's code:

    {% assign p_annual = all_products[section.settings.paid_product_annual] %}
    {% assign p_free = all_products[section.settings.free_product] %}

        {% if section.settings.productlink1label != blank %}
            <button class="btn"
                 type="submit" 
                 name="paid-plan" 
                 id="paid-plan-option-annual" 
                 data-variant-id="{{ p_annual.selected_or_first_available_variant.metafields.subscriptions.discount_variant_id }}" 
                 data-variant-interval-value="{{ p_annual.metafields.subscriptions.shipping_interval_frequency }}" 
                 data-variant-interval-unit="{{ p_annual.metafields.subscriptions.shipping_interval_unit_type }}"
                 data-quickadd-id="{{ p_annual.selected_or_first_available_variant.id }}"
                 data-quickadd-properties
             >
                        {{ p_annual.selected_or_first_available_variant.price | money_without_trailing_zeros }}{{ section.settings.productlink1label }}
             </button>
        {% endif %}

The code grabs the item by the ID and makes an AJAX request.

// quick add
    _document.on('click', '[data-quickadd-id]', function() {
        let _this = $(this);

        loadingBarTrigger('start');

        itemAdd(
            _this.attr('data-quickadd-id'), 
            _this.attr('data-quickadd-properties'), 
            (_this.attr('data-quickadd-quantity'))
                ? _this.attr('data-quickadd-quantity')
                : 1, 
            (!html.is('#cart')) ? true : false,
            (html.is('#cart')) ? true : false
        );
    });

inside of cart function:

onst itemAdd = (variantId, properties, qty, openCart, reloadPage) => {
        $.ajax({
            type: 'POST',
            dataType: 'html',
            url: `/cart/add.js`,
            data: 
                {
                    id: variantId,
                    quantity: qty,
                    properties: (properties) 
                        ? JSON.parse(properties) : null
                },
                
            error: function(data) {
                console.error(data);

                loadingBarTrigger('done');
            },
            success: function() {
                loadingBarTrigger('move');

                $.ajax({
                    url: '/cart',
                    dataType: 'html',
                    error: function(data) {
                        console.error(data);

                        loadingBarTrigger('done');
                    },
                    success: function(data) {
                        let minicartContent = $('#minicart-content');
                        let cartItemsHtml = $(data).find('#cart-content #cart-items').html();

                        // insert or prepend cart HTML
                        (minicartContent.find('#cart-items').length)
                            ? minicartContent.find('#cart-items').html(cartItemsHtml)
                            : minicartContent.prepend(cartItemsHtml);

                        // remove giftbox content if exists
                        (minicartContent.find('#cart-giftbox .item-info').length)
                            ? minicartContent.find('#cart-giftbox .item-info').remove()
                            : '';

                        loadingBarTrigger('done');
                        cartTotalUpdate();

                        // open cart
                        (openCart && !html.is('#cart'))
                            ? minicartTrigger.trigger('click') : '';

                        (reloadPage)
                            ? location.reload() : '';
                    }
                });
            }
        });
    }

I know this is possible with the AJAX API update last year. But I'm unsure how to implement it in my store. The data-variant-id only accepts one value if I'm not mistaken. And what's data-variant-id es first gets precedence. I guess the main thing is that I'm unsure how to send json with the submit button.

Any ideas?

Share Improve this question asked Jun 16, 2021 at 19:13 JasonJason 751 gold badge3 silver badges9 bronze badges 1
  • I think the best way is clearly answered here: stackoverflow./a/72915384/17860991 – Musaib Mushtaq Commented Oct 5, 2022 at 8:58
Add a ment  | 

2 Answers 2

Reset to default 6

In a classic add product form, you can replace: <input type="hidden" name="id" value="{{ product.selected_or_first_available_variant.id }}" disabled> with:

<input type="hidden" name="items[0][quantity]" value="1">
<input type="hidden" name="items[0][id]" value="ID_OF_YOUR_FIRST_PRODUCT_VARIANT">
<input type="hidden" name="items[1][quantity]" value="1">
<input type="hidden" name="items[1][id]" value="ID_OF_YOUR_SECOND_PRODUCT_VARIANT">

If you want to add the products in ajax, you just have to use the "FormData" object in the body of the request:

let addToCartForm = document.querySelector('form[action$="/cart/add"]');
let formData = new FormData(addToCartForm);
fetch(window.Shopify.routes.root + 'cart/add.js', {
  method: 'POST',
  body: formData
})
.then(response => {
  return response.json();
})
.catch((error) => {
  console.error('Error:', error);
});

I think you need to check and default Shopify documentation and make changes to the code according to the documentation. Here into documentation they clearly mentioned how you can add multiple product using AJAX API.

https://shopify.dev/docs/themes/ajax-api/reference/cart

So you can check and update the code and past the multiple variants to items array like this demo code.

jQuery.post('/cart/add.js', {
  items: [
    {
      quantity: quantity,
      id: 1st ID
    },
    {
      quantity: quantity,
      id: 2nd ID
    },
    {
      quantity: quantity,
      id: 3rd ID
    }
  ]
});

本文标签: javascriptHow to Add Multiple Products to Shopify Cart with One Button ClickStack Overflow