Overview
This implementation allows users to manually enter their shipping details (ZIP code, country, and province) and fetch real-time shipping rates on a Shopify product page. The rates are retrieved from Shopify’s shipping API, and the product is temporarily added to the cart for accurate calculations.
How It Works
A form is provided where users enter their ZIP code, country, and province.
When the form is submitted, JavaScript captures the input values and sends a request to Shopify to add the product temporarily to the cart.
After adding the product, Shopify’s
/cart/shipping_rates.json
API is called with the provided shipping details.The API response is displayed, showing available shipping methods and costs.
The product is then removed from the cart for cleanup.
The response is logged in the browser console for debugging.
Installation
Step 1: Add the Form to Your Shopify Product Page
Include this form inside product.liquid
or another relevant template file:
Step 2: Add the JavaScript Code
Place this JavaScript inside your Shopify theme file (theme.liquid
) or an external JavaScript file.
document.addEventListener('DOMContentLoaded', function () {
// Get the form and shipping rates container
const shippingForm = document.getElementById('shipping-form');
const shippingRatesContainer = document.getElementById('shipping-rates');
// Event listener for form submission
shippingForm.addEventListener('submit', function (event) {
event.preventDefault(); // Prevent default form submission
const zip = document.getElementById('zip').value;
const country = document.getElementById('country').value;
const province = document.getElementById('province').value;
const variantId = {{ product.selected_or_first_available_variant.id }};
// Add the product to the cart (temporarily) to calculate shipping rates
fetch('/cart/add.js', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
items: [{ id: variantId, quantity: 1 }]
})
})
.then(() => {
// Fetch shipping rates based on user input
return fetch(`/cart/shipping_rates.json?shipping_address[zip]=${zip}&shipping_address[country]=${country}&shipping_address[province]=${province}`);
})
.then(response => response.json())
.then(data => {
// Log response for debugging
console.log("Shipping Rates API Response:", data);
// Display shipping rates
if (data.shipping_rates && data.shipping_rates.length > 0) {
let ratesHTML = 'Shipping Rates
';
data.shipping_rates.forEach(rate => {
ratesHTML += `${rate.name}: ${rate.price}
`;
});
shippingRatesContainer.innerHTML = ratesHTML;
} else {
shippingRatesContainer.innerHTML = 'No shipping rates available.
';
}
})
.catch(error => {
console.error("Error fetching shipping rates:", error);
shippingRatesContainer.innerHTML = 'Error calculating shipping rates. Please try again.
';
})
.finally(() => {
// Remove the product from the cart (cleanup)
fetch('/cart/clear.js', {
method: 'POST',
headers: { 'Content-Type': 'application/json' }
});
});
});
});
Debugging & Testing
To test if everything is working correctly:
Open your website.
Right-click anywhere and select Inspect to open DevTools.
Go to the Console tab.
Submit the form and check for the log:
Shipping Rates API Response: { shipping_rates: [...] }
This helps debug any missing shipping rates.
Customization
Change Default Product Quantity
Currently, the script adds 1 unit of the product to the cart for rate calculation. To modify this, change:
quantity: 1
Increase or decrease the quantity as needed.
Modify Form Fields
You can customize the form labels, inputs, or add dropdowns for country selection.
Ensure the ID values in the JavaScript match those in the form (
zip
,country
,province
).
Troubleshooting
1. No Shipping Rates Available
Make sure the shipping zones and rates are configured in Shopify Admin.
Check the browser console for API response logs.
2. Shipping Rates API Returns an Error
Ensure that the ZIP, country, and province values are valid.
Double-check Shopify settings under Settings > Shipping and Delivery.
3. Debugging API Requests
Use
console.log("Shipping Rates API Response:", data);
in the script.Open DevTools > Network Tab and inspect the requests made to Shopify.
Conclusion
This script provides a seamless way to fetch real-time shipping rates on the Shopify product page, allowing customers to calculate costs before checkout.
Let me know if you need further modifications or enhancements! 🚀