Hi,
I am new to shopify and Javascript, so I apologise if my code looks terrible.
Below is the code I am using to remove an item from the cart of a customer when a product offer has ended and a countdown timer in the product page hit zero.
I am doing so by comparing the current date with the end date of the product offer set in the product metafield:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'GET',
url: '/cart.js',
dataType: 'json',
success: function(cart) {
var current_time = new Date().getTime() / 1000;
$.each(cart.items, function(index, item) {
var timer_ends_at = new Date(product.metafields.custom.countdown_timer_date).getTime() / 1000;
if (timer_ends_at < current_time) {
$.ajax({
type: 'POST',
url: '/cart/change.js',
data: {quantity: 0, id: item.id},
dataType: 'json',
success: function(cart) {
}
});
}
});
}
});
});
</script>
Unfortunately I get the error: Uncaught TypeError: Cannot read properties of undefined (reading ‘metafields’) ,and the code doesn’t work.
If I set a specific end date in the code, it works as intended and the item in the customer cart is removed, but it’s not what I want.
I want the end date to be different for every product, and I don’t want to manually change the code all the time.
I had a look around and I found out that metafield are not accessible in JS. Is there any workaround?
Can I achieve the same as the code above using liquid instead of Javascript? if so, could someone help me with the code, I’m not very good with liquid yet.
Thanks