Discuss and resolve questions on Liquid, JavaScript, themes, sales channels, and site speed enhancements.
I can call Ajax API to add a product to cart then call below code to navigate users to the checkout page
const response = await fetch('/cart', {
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
method: 'POST',
body: 'updates%5B%5D=1&updates%5B%5D=1&updates%5B%5D=1&checkout=',
});
location.href = response.url;
But I wondering if there is a better way since this code is quite tricky
Solved! Go to the solution
This is an accepted solution.
You can try this one. It will do the same based on the official cart API
// Function to add item to cart and redirect to checkout
async function cartToCheckout(variantId, quantity) {
try {
// Add item to cart
const addToCartResponse = await fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
items: [{
id: variantId,
quantity: quantity
}]
})
});
if (!addToCartResponse.ok) {
throw new Error('Failed to add item to cart');
}
// Redirect to checkout
window.location.href = '/checkout';
} catch (error) {
console.error('Error:', error);
// Handle error (e.g., show error message to user)
}
}
// How to use
cartToCheckout(12345678, 1); // Replace 12345678 with actual variant ID
Do let me know if it works.
Thanks.
This is an accepted solution.
You can try this one. It will do the same based on the official cart API
// Function to add item to cart and redirect to checkout
async function cartToCheckout(variantId, quantity) {
try {
// Add item to cart
const addToCartResponse = await fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
items: [{
id: variantId,
quantity: quantity
}]
})
});
if (!addToCartResponse.ok) {
throw new Error('Failed to add item to cart');
}
// Redirect to checkout
window.location.href = '/checkout';
} catch (error) {
console.error('Error:', error);
// Handle error (e.g., show error message to user)
}
}
// How to use
cartToCheckout(12345678, 1); // Replace 12345678 with actual variant ID
Do let me know if it works.
Thanks.
Thanks, dude! it works perfectly! I'm wondering why I wrote lines of very complicated code for just a line of "window.location.href = '/checkout'" 🤣
Hey Community! As the holiday season unfolds, we want to extend heartfelt thanks to a...
By JasonH Dec 6, 2024Dropshipping, a high-growth, $226 billion-dollar industry, remains a highly dynamic bus...
By JasonH Nov 27, 2024Hey Community! It’s time to share some appreciation and celebrate what we have accomplis...
By JasonH Nov 14, 2024