How to change multiple cart items at once?

Solved
Highlighted
New Member
3 1 0

Hello, I am having a bit of trouble figuring this one out.

 

On our site, I have it set where products are either set to "instock" or "outofstock" based on quantity. I then gather a list of the outofstock Ids and want to post a remove item from cart action for each one.

 

I have tried a couple of methods of doing so, the first just doesn't work, while the other only removes the first matching item. (I am thinking it's due to too many calls at once? Though I'm unsure)

 

This is the code I tried to edit several IDs at once, which failed.

      jQuery.post('/cart/change.js', {
  items: [
    {
      quantity: 0,
      id: oos_ID[0]
    },
    {
      quantity: 0,
      id: oos_ID[1]
    },
    {
      quantity: 0,
      id: oos_ID[2]
    },
    {
      quantity: 0,
      id: oos_ID[3]
    }
  ]
});

This is the loop I tried to do call for each out of stock item, which only does the first matching one.

 	for (var i = 0; i < oos_ID.length; i++) {
    jQuery.post('/cart/change.js', { quantity: 0, id: oos_ID[i] });
	}

This is the whole bit of code for this section, with the loop.

let oos_ID = [];
const oos_items_availability = document.querySelectorAll('ul li meta[itemprop~="availability"]');
const oos_items_ID = document.querySelectorAll('ul li meta[itemprop~="productID"]');
var cart_items = document.querySelectorAll('.cart_item .item_title');

	for (var i = 0; i < oos_items_availability.length; i++) {
      if( oos_items_availability[i].outerHTML.indexOf('OutOfStock') >= 0){
	  //console.log('oos_items_availability: ', oos_items_availability[i].outerHTML);
      //console.log('oos_items_ID: ', oos_items_ID[i].outerHTML);
      oos_ID.push(oos_items_ID[i].outerHTML.replace('<meta itemprop="productID" content="', '').replace('"/>','').replace('">',''));
}
	}
    
 	for (var i = 0; i < oos_ID.length; i++) {
    jQuery.post('/cart/change.js', { quantity: 0, id: oos_ID[i] });
	}

I feel like I should note that our site contains a ton of custom code, all of our products are on a single page. We've been experiencing some issues where customers are able to buy items that shouldn't be able to, so that is the purpose of this whole remove from cart functionality.

 

P.S. I plan to tidy up my code after I get things working as they should

 

Thanks!

0 Likes
Highlighted
New Member
2 0 0

did you ever figure this out? i have the exact same issue. trying to remove paired cart items with change.js. only the first one gets executed, even though the response for both show a success.

0 Likes
Highlighted
New Member
3 1 0

This is an accepted solution.

You have wonderful timing. I am in the middle of rewriting our entire site now, and came back to try to solve this problem with success, finally.

Here's two functions, one for removing 1 item, and 1 for removing a list of IDs of unknown length. I have not done much testing with this, but what I have tested works as expected.

 

This is pure JS, no jquery needed.

 

 

  const removeItemFromCart = (productID) => {
    let formData = {
        'updates': {
            [parseInt(productID)]: 0
        }
    };

    let info = fetch('/cart/update.js', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    }).then(response => response.json()).then(data => {
        return data
    }).catch((error) => {
        console.error('Error:', error);
    });

}
//removeItemFromCart(##############);

const removeSeveralFromCart = (...productIDS) => {
    let formData = {
        'updates': {}
    };

    var productID;
    for (productID in productIDS) {
        formData['updates'][parseInt(productIDS[productID])] = 0;
    }

    let info = fetch('/cart/update.js', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    }).then(response => response.json()).then(data => {
        return data
    }).catch((error) => {
        console.error('Error:', error);
    });

}
//removeSeveralFromCart(##############,##############,##############,##############);

 

 

 

If you need some help, I can do my best to help out!

Good luck

 

James

0 Likes
Highlighted
New Member
2 0 0

Thank you for the reply. I needed to use item keys and found this SO post which saved me, also using update instead of change: https://stackoverflow.com/a/60622488 The docs don't indicate that you can use keys in update.js

Post an updates object with key-value pairs. The key is the line item's variant_id.

but the SO post indicates:

One point that the documentation omits is that you can use either the variant ID or the line-item's 'key' value as the key for the payload.

so I thought I was trapped with multiple calls to change.js.

0 Likes