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
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’” 