Is there a way to access data from a different cart template containing personalized values on Shopify?

After analyzing the values required from product.json, I realized that the current method is not efficient. The client-side ends up processing unnecessary information and every new product or option adds to the request load. Below is the script responsible for this process:

  var CompareTotal = 0;

$.each(cart.items, function(index, cartItem) {

  var varID = cartItem.variant_id;
  var comparePrice= '';
  var TotalcomparePrice = '';

  $.ajax({
    url: '/products/' + cartItem.handle + '.js', 
    dataType: 'json',
    async: false, 
    success: function(product){ 
      product.variants.forEach(function(variant) {
        if ( variant.id == varID && variant.compare_at_price !== 0){
          comparePrice = variant.compare_at_price;
          TotalcomparePrice = cartItem.quantity * comparePrice;
       CompareTotal = CompareTotal + TotalcomparePrice;             
          return false;  
        }
      });
     }
  });});

To optimize these processes and enhance speed, I implemented an alternative cart template containing all necessary values. Now, the goal is to retrieve these values by replacing the previous approach. However, using dataType: 'JSON' is not possible as the default data comes from the server-side. Here is a glimpse of the alternative template:

{ "token": "eacf539f884b717a2a74ac775b9b8923", "note": "", "attributes": {}, "original_total_price": 2390, "total_price": 2390, "total_discount": 0, "total_weight": 0.0, "item_count": 2, "items": [{ "id": 31286186180719, "properties": { }, "quantity": 2, "variant_id": 31286186180719, "key": "31286186180719:404d70730b155abbf5e62b28445537ae", "title": "RO - 1. Darkest Brown \u0026 Dark Auburn Mix", "compare_at_price": 1595, "compare_line_price": 3190, "price": 1195, "original_price": 1195, "discounted_price...

I have successfully fetched all necessary information via console log after setting up the request. Here's how it was done:

$.ajax({
type: 'GET',
url: '/cart?view=data',
success: function(response) {
    json_response = JSON.parse(response);
    console.log( 'response', json_response );
},
error: function(status) {
    console.warn( 'ERROR', status );
}});

The next step involves extracting the values of compare_line_price for each product and total_compare_price for the entire cart. With handlebars, I can then display them. As a self-taught individual, each progression in this aspect presents challenges. Any guidance on the way forward would be greatly appreciated.

    {%- layout none -%}
{%- assign cartJson = cart | json -%}
{%- assign cartToken = cartJson | split:'token":"' | last | split:'"' | first | json -%}
{% assign total_cart_compare_price = 0 %}
{
    "token": {{ cartToken }},
    "note": {{ cart.note | json }},
    "attributes": {{ cart.attributes | json }},
    "original_total_price": {{ cart.original_total_price | json }},
    "total_price": {{ cart.total_price | json }},
    "total_discount": {{ cart.total_discount | json }},
    "total_weight": {{ cart.total_weight | json }},
    ...

Here's a preview of the alternative cart template.

Answer №1

Ensure your cart liquid is updated as shown below:

{%- layout none -%}
{%- assign cartJson = cart | json -%}
{%- assign cartToken = cartJson | split:'token":"' | last | split:'"' | first | json -%}
{% assign total_cart_compare_price = 0 %}
{
    "token": {{ cartToken }},
    "note": {{ cart.note | json }},
    "attributes": {{ cart.attributes | json }},
    "original_total_price": {{ cart.original_total_price | json }},
    "total_price": {{ cart.total_price | json }},
    "total_discount": {{ cart.total_discount | json }},
    "total_weight": {{ cart.total_weight | json }},
    "item_count": {{ cart.item_count | json }},
    "items": [
        {%- for item in cart.items -%}
        {
        "id": {{ item.id | json }},
        "properties": {
            {%- for prop in item.properties -%}
            {{ prop | first | json }}:{{ prop | last | json }}{% unless forloop.last %},{% endunless %}
            {%- endfor %}
        },
        "quantity": {{ item.quantity | json }},
        "variant_id": {{ item.variant_id | json }},
        "key": {{ item.key | json }},
        "title": {{ item.title | json }},
        "compare_at_price": {{ item.variant.compare_at_price | json }},
        "compare_line_price": {{ item.variant.compare_at_price | times: item.quantity | json }},
        "price": {{ item.price | json }},
        "original_price": {{ item.original_price | json }},
        "discounted_price": {{ item.line_price | json }},
        "line_price": {{ item.line_price | json }},
        "original_line_price": {{ item.original_line_price | json }},
        "total_discount": {{ item.total_discount | json }},
        "discounts": {{ item.discounts | json }},
        "sku": {{ item.sku | json }},
        "grams": {{ item.grams | json }},
        "vendor": {{ item.vendor | json }},
        "taxable": {{ item.taxable | json }},
        "product_id": {{ item.product_id | json }},
        "gift_card": {{ item.gift_card | json }},
        "url": {{ item.url | json }},
        "image": {{ item.variant.image | json }},
        "handle": {{ item.product.handle | json }},
        "requires_shipping": {{ item.requires_shipping | json }},
        "product_type": {{ item.product.type | json }},
        "product_title": {{ item.product.title | json }},
        "variant_title": {{ item.variant.title | json }},
        "variant_options": {{ item.variant.options | json }}
        }{% unless forloop.last %},{% endunless %}

{%- if item.variant.compare_at_price != blank -%}
  {%- assign compare_price = item.variant.compare_at_price | times: item.quantity -%}
{%- else -%}
  {%- assign compare_price = item.line_price -%}
{%- endif -%}
{% assign total_cart_compare_price = total_cart_compare_price | plus: compare_price %}

        {%- endfor -%}
    ],
    "total_compare_price": {{ total_cart_compare_price | json }},
    "currency": {{ cart.currency.iso_code | json }},
    "items_subtotal_price": {{ cart.items_subtotal_price | json }},
    "cart_level_discount_applications": {{ cart.cart_level_discount_applications | json }}
}

Next, attempt to make use of the AJAX request provided below:

$.ajax({
  type: 'GET',
  url: '/cart?view=data',
  success: function(response) {
    json_response = JSON.parse(response);
    console.log( 'response', json_response );

    // Your total compare price will be displayed here
    console.log( 'total_compare_at_price', json_response.total_compare_price );
  },
  error: function(status) {
    console.warn( 'ERROR', status );
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PHP and Bootstrap combine in this dynamic carousel featuring thumbnail navigation

Looking to create a dynamic bootstrap carousel with image thumbnails at the bottom? After exploring various code snippets and solutions, I stumbled upon this link. While the code worked, I found the thumbnails to be too small. Below are the functions I use ...

Dynamically loading an AngularJS controller

I am faced with the challenge of integrating an Angular app with dynamically loaded controllers into an existing webpage. Below is a code snippet where I have attempted to achieve this based on my understanding of the API and some research: // Create mod ...

Error: The variable "user" has not been declared in server.js when using passportjs

As a novice with limited experience and a tendency to borrow code snippets from various sources, I'm struggling to identify the root cause of the Reference Error: User is not defined. This particular error crops up when I try to input or submit a new ...

Having trouble establishing a connection between MongoDB and a Node.js Express server on my local machine

While attempting to establish a connection between mongoDB and nodejs express using the post method, I added a logger that should display a message confirming that the database is connected once nodejs listens to mongoDB. However, I encountered an issue wh ...

Leveraging the Wikia API

I've been attempting to utilize the X-men API on Wikia in order to gather the name and image of each character for use in a single page application using JavaScript. You can find the link to the wiki page here: Despite my efforts, I am struggling to ...

Manipulating strings by extracting a targeted statement

Is there a way to extract just the link from each line in order to get the desired output? For example, starting with this input: "url": "https://i.ytimg.com/vi/XGM6sHIJuho/hqdefault1.jpg", "og:image": "https://i.ytimg.com/vi/XGM6sHIJuho/hqdefault2.jpg" ...

Creating an Organized Framework for a Website Application

In my particular case, I am utilizing an AngularJS application, although I believe this inquiry is relevant to any Single Page App. I've implemented a component structure as outlined in various resources such as this and this. Let's assume I ha ...

When the button is clicked, the JavaScript function is not being executed

I'm having a strange issue with my second button not working as expected. Despite appearing to be straightforward, the "Reset" button does not seem to be triggering the clear() function. Within the HTML code, I have two buttons set up to interact wit ...

Verifying in PHP if the request is intended for a JavaScript worker

After doing my research on MDN for the referrer-policy, as well as searching through Google, DuckDuckGo and Stack Overflow, I still find myself stuck on a seemingly simple yet elusive issue. Journey of Data the browser sends a request to the server the ...

Discovering the specific structure of an object in a JSON file can be tricky when working with Node.js. This guide will

Here is the data from my JSON file: [ {"name":"a","queryname":"Query_1","type":"user","context":"novell","searchsubcontainer":false}, {"name":"aa","queryname":"Query_2","type":"user","context":"novell","searchsubcontainer":true}, {"name":"admi ...

Tips for preventing Chrome from masking the background image and color on an autofill input

Google Chrome Browser has caused the background-color and background-image effects to be removed from the Username and Password input fields. Before autocomplete https://i.stack.imgur.com/Ww7Hg.png After autocomplete https://i.stack.imgur.com/hbG2C.png ...

JavaScript code for computing the error function of Gauss

Are there any freely available implementations of the Gauss error function in JavaScript under a BSD or MIT license? ...

Discover the ultimate strategy to achieve optimal performance with the wheel

How can I dynamically obtain the changing top position when a user moves their mouse over an element? I want to perform some checks whenever the user scrolls up, so I tried this code: HostListener('window:wheel', ['$event']) onWindowS ...

Values are being set back to '1' within the popup dialog

After recently incorporating Twitter Bootstrap into my web app project, everything seemed to be going smoothly until I encountered an issue with a modal window. Following the Bootstrap documentation, I set up a button that triggers a modal window to appea ...

Color Your Plone Website with a Custom JavaScript Colorscheme

Currently, I have implemented a custom theme by registering the javascript in the skin.xml file and then creating a specific folder within the browser to store the script. Below is the script shared by one of the users: $(document).ready(function(){ ...

Pressing a shortcut key will direct the focus to the select tag with the help of Angular

I was trying to set up a key shortcut (shift + c) that would focus on the select tag in my form when pressed, similar to how tab works. Here is the HTML code for my form's select tag: <select id="myOptions"> <option selected> Opti ...

Comparing Ajax and Socket.io: A Comprehensive Analysis

As I work on developing a web application, I find myself in the dilemma of choosing the most suitable method for my project. The main goal is to provide users with notifications sourced from requests made to external servers. My node.js application collec ...

Bringing JSON data from a PHP file into a Swift project

I currently have a website running on a MySQL database. Now, I am working on developing an iOS app using Swift to interact with this database. To retrieve information from the database and add new data, I plan to use a PHP file to generate a Json file whic ...

How can array splice be utilized to substitute the final element within an array?

My array is structured like this: Array ( [0] => Credit Card Type [1] => MasterCard ) Array ( [0] => Credit Card Number [1] => xxxx-1111 ) Array ( [0] => Processed Amount [1] => $106.91 ) Array ( [0] => Transaction Id [1] => 501105 ...

Choose the element before and add a style effect with CSS

I'm trying to create a layout with 3 <div> elements in one horizontal line, each with a width of 33.33%. When hovering over one div, I want its width to expand to 50% while the other two shrink to 25%. <div id="A"></div> <div id= ...