Need Help Saving Cookie Values and UTM Parameters to Cart Attributes in Shopify

Sharif7
Visitor
2 0 0

Hey Shopify Community,

I hope you're all doing well. 
First of all, I have a code that saves cookie values and UTM parameters from the visitor's browser to local storage with the key "sharif_attribution".

 

Then I implemented a code in my Shopify theme (main-cart-items.liquid file) between the <form> and </form> tags to retrieve data from the visitor's local storage and save it as a cart attribute:

 

 

<script>
document.addEventListener("DOMContentLoaded", function() {
  // Get the value from local storage
  var sharifAttribution = localStorage.getItem("sharif_attribution");

  // Update the note_attributes input field
  var noteAttributesInput = document.getElementById("your-name");
  noteAttributesInput.value = sharifAttribution;

  // Hide the input field
  noteAttributesInput.style.display = "none";
});
</script>

<p class="cart-attribute__field">
  <input class="ctuClass" id="your-name" type="text" name="attributes[sharif_attribution]" value="{{ cart.attributes["sharif_attribution"] }}">
</p>

 

 

I've noticed that this code only saves the data if a visitor adds a product to their cart and then visits the cart page. What I'm aiming for is to have the data saved even if a visitor directly checkout after adding the product to cart from the product page ( without visiting the Cart Page ) or clicks the "Buy Now" button from a product page.

 

Additionally, I'd like to know if there's a way to save information from local storage to Cart Attributes without using an input field. Any suggestions or code improvements would be highly appreciated!

Thank you in advance for your time and assistance.

Replies 2 (2)

Liam
Shopify Staff
2731 298 769

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.

Liam | Developer Advocate @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

Sharif7
Visitor
2 0 0

Hi Liam,

Thank you for your response and the detailed code snippet. I followed your instructions.

At first I inserted :

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

 


this script in the Shopify theme.liquid file under the Head tag.


Then, I implement your code to Assets > global.js file with replaced the CSS class ( .shopify-payment-button ) .

 

$(document).ready(function() {
  $('[name="add"], .shopify-payment-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('shopify-payment-button')) {
      window.location.href = '/checkout';
    }
  });
});

 

 

After applying the code, I noticed that the 'Add to Cart' button is unresponsive. I also checked from Chrome inspect > Network tab, and I can see that it's updating the cart attributes, but nothing happens when I click the 'Add to Cart' button.
I noticed that this behavior for "e.preventDefault();" this line of code. When I remove this line, the 'Add to Cart' button functions as expected and updated the cart attributes perfectly.

When I click the 'Buy Now' button ( Shopify dynamic checkout buttons ) , which first takes me to the checkout page. But then, it quickly redirect me back to the homepage before checkout page load. I've tried different approaches, including using and not using the 'e.preventDefault();' code, but the problem still happens.

I am new to this, so it would be greatly appreciated if you could kindly provide me with the code and a step-by-step guide.

Your assistance is immensely valuable. Thank you once again for your time and support.