Hi Sharif7,
To achieve what you’re looking for, you could use the AJAX API to update the cart attributes directly when a product is added to the cart, regardless of whether the Cart page is visited or not. This can be done by listening to the ‘Add to Cart’ or ‘Buy Now’ button click event, and then updating the cart attributes accordingly. Here is an example of how you could do this:
$(document).ready(function() {
$('[name="add"], .buy-now-button').on('click', function(e) {
e.preventDefault();
// Get the value from local storage
var sharifAttribution = localStorage.getItem("sharif_attribution");
// Update the cart attributes
$.ajax({
type: 'POST',
url: '/cart/update.js',
data: {
attributes: {
sharif_attribution: sharifAttribution
}
},
dataType: 'json'
});
// If it's the 'Buy Now button, redirect to checkout
if ($(this).hasClass('buy-now-button')) {
window.location.href = '/checkout';
}
});
});
Just replace .buy-now-button with the actual class of your ‘Buy Now’ button. This script should be placed in the product template or in a global script file.
As for your second question, the cart attributes need to be sent to the server, which usually requires an HTML form. However, the above AJAX method allows you to send data to the server without the need for an actual form or input field in your HTML. This is because AJAX allows for asynchronous communication with the server, meaning it can send and retrieve data without requiring a page reload. It can send the data straight from your JavaScript code to the server.
I hope this helps! Let me know if you have any further questions.