Adding Product Metafields and update the cart via AJAX

Adding Product Metafields and update the cart via AJAX

asprincean
New Member
4 0 0

Hi All,

 

I am quite new in Shopify and I hope someone can help me with an idea.

I am trying to enhance the cart functionality by integrating product add-ons stored in metafields. I’ve updated my Liquid template to display these add-ons, but I need help with the JavaScript to handle add-on selections and update the cart total dynamically.

Here's a brief overview of my setup:

Liquid Template: Displays add-ons for each cart item using metafields.
Javascript: Needs to update the cart total when add-ons are selected or deselected.
I'd appreciate any guidance or examples on implementing the JavaScript part, especially for updating the cart total and handling interactions with Shopify's AJAX API if necessary.

Thanks in advance for your help!

Replies 4 (4)

Small_Task_Help
Shopify Partner
528 16 36

Hi,

 

Please share your store url. If you want you can contact us details given at Signature 

Click here to Contact and Get Shopify Store Help
E-mail - hi@ecommercesmalltask.com
We are Shopify Experts   from Ecommerce Small Task Company.
asprincean
New Member
4 0 0
asprincean
New Member
4 0 0

Also, the UI I currently made in a copy of the theme and looks like this:

asprincean_0-1720174761558.png

 





asprincean
New Member
4 0 0

This is what I have done so far:

{{ 'component-cart-addons.css' | asset_url | stylesheet_tag }}

<div class="cart-addons">
<h2 class="cart-addons__title">Enhancements</h2>
{% for item in cart.items %}
{% assign product_addons_metafield = item.variant.metafields.product_add_ons.addon.value %}
<ul class="cart-addons-list" id="addon-checkboxes">
{% if product_addons_metafield %}
{% for addon in product_addons_metafield %}
<li class="cart-addon">
<div class="cart-addon__details">
<h4 class="cart-addon__title">{{ addon.title.value }}</h4>
{% assign description = addon.description | metafield_tag %}
<p class="cart-addon__description">{{ description }}</p>
</div>
<div class="cart-addon__right">
<label for="addon-checkbox-{{ forloop.index }}" class="cart-addon__label">
Add for {{ addon.price.value | money }}
</label>
<input
type="checkbox"
id="addon-checkbox-{{ forloop.index }}"
class="cart-upsell-checkbox"
data-price="{{ addon.price.value }}"
data-variant-id="{{ item.variant.id }}"
data-enhancement-name="{{ addon.title }}"
>
</div>
</li>
{% endfor %}
{% else %}
<p>No add-ons available for this product.</p>
{% endif %}
</ul>
{% endfor %}
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
const checkboxes = document.querySelectorAll('.cart-upsell-checkbox');

checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
const price = parseFloat(this.dataset.price);
const variantId = this.dataset.variantId;
const enhancementName = this.dataset.enhancementName;

console.log('Checkbox changed:', { variantId, price, enhancementName });

// Calculate the current cart total price
let currentTotal = {{ cart.total_price }}

// Adjust the total price based on whether the checkbox is checked or unchecked
if (this.checked) {
currentTotal += price;
} else {
currentTotal -= price;
}

// Update the cart total using AJAX
updateCartTotalViaAjax(currentTotal);
});
});

function updateCartTotalViaAjax(newTotal) {
// Prepare the data to send
var requestData = JSON.stringify({ total_price: newTotal });
console.log('Request Data:', requestData);

// Send the AJAX request to update the cart total
var xhr = new XMLHttpRequest();
xhr.open('POST', '/cart/update.js', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
var updatedCart = JSON.parse(xhr.responseText);
console.log('Cart updated successfully via AJAX:', updatedCart);
// Log the updated total price from Shopify's response
console.log('Updated Total Price:', updatedCart.total_price);
} else {
console.error('Error updating cart via AJAX:', xhr.statusText);
console.log('Response:', xhr.responseText); // Log the full response for debugging
}
};
xhr.onerror = function() {
console.error('Request failed');
// Handle error
};
xhr.send(requestData); // Send the prepared JSON stringified data
}
});
</script>