skip to Main Content

I am attempting to post 2 items to a shopping cart, in one click. I’ve built a form with hidden checkboxes that carry the relevant product attributes I need to do that. I have a loop going over the form’s child checkboxes to pull that info and invoke the function for the post request.

The problem is that sometimes it does add both items (yay!) but sometimes it’ll load only the first item and sometimes only the second item. There’s no error code in the console for me to go off of so I’m wondering what I’m missing.

EDIT: 19 hours in. I’m thinking the issue is coming from the function that opens the cart that is firing when the first item is returned. Both of the calls are being return successfully but that code is interrupting it being added to the cart.

EDIT 2: This post describes the issue I’m having. I need to make one request and then move on to the next one. I think I’m going to have to build an array with the items from the form.

My JS

const freeAddOnForm = document.getElementById('free-addon-form'),
      freeAddOnButton = freeAddOnForm[2];

function getDataForm(e) {
    e.preventDefault();

    loadingBarTrigger('start');

    for(let i = 0; i < 2; i++) {
        itemAdd(
            freeAddOnForm[i].getAttribute('data-quickadd-id'), 
            freeAddOnForm[i].getAttribute('data-quickadd-properties'), 
            (freeAddOnForm[i].getAttribute('data-quickadd-quantity'))
                ? freeAddOnForm[i].getAttribute('data-quickadd-quantity')
                : 1, 
            (!html.is('#cart')) ? true : false,
            (html.is('#cart')) ? true : false
        )
    }   
}

document.addEventListener('DOMContentLoaded', function (){
    freeAddOnButton.addEventListener('click', getDataForm, false);
})

The itemAdd function that makes the post request to the cart:

const 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() : '';
                }
            });
        }
    });
}

2

Answers


  1. Chosen as BEST ANSWER

    Ended up putting both items as objects into an array and sending them to the Shopify AJAX api together. Seems to work, a couple little bugs to hammer out with the slide out cart at the end of the function.

    const itemsAddAjax = (itemsQueue, openCart, reloadPage) => {
            console.log(itemsQueue)
    
            $.post(`/cart/add.js`, {
                items: [
                    {
                    quantity: itemsQueue[0].qty,
                    id: itemsQueue[0].id,
                    properties: (itemsQueue[0].properties) 
                        ? JSON.parse(itemsQueue[0].properties) : null
                    },
                    {
                    quantity: itemsQueue[1].qty,
                    id: itemsQueue[1].id,
                    properties: (itemsQueue[1].properties) 
                        ? JSON.parse(itemsQueue[1].properties) : null
                    }
                ],
                
                error: function(items) {
                    // console.error(items);
    
                    loadingBarTrigger('done');
                },
                success: function() {
                    loadingBarTrigger('move');
                  
    
                    $.ajax({
                        url: '/cart',
                        dataType: 'html',
                        error: function(items) {
                            console.error(items[0]);
                            loadingBarTrigger('done');
                        },
                        success: function(items) {
    

  2. I think the easy and Simple way is to use the following code and add number of items in "items" array with their respective data.

    let formData = {
     'items': [{
      'id': 36110175633573,
      'quantity': 2
      },
    {
      'id': 36110175623388,
      'quantity': 1
      }
    ]
    };
    
    fetch(window.Shopify.routes.root + 'cart/add.js', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formData)
    })
    .then(response => {
      return response.json();
    })
    .catch((error) => {
      console.error('Error:', error);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search