When working in Shopify, I have found that I am able to easily access a JSON object from the browser console, however I have run

Currently, I am utilizing the GET/cart.js call in an asset on my theme to retrieve the cart contents in a JSON object format as shown below:

var response = jQuery.getJSON('/cart.js');

Afterward, I attempt to display the contents of the object in the console like this (within the same snippet file, immediately after making the call):

$( document ).ready(function() {
    console.log(response.responseJSON.items[0]);
});

However, when I do so, I encounter a

TypeError: response.responseJSON is undefined
error in the console. Strangely enough, if I try to log the same thing again within the console (
console.log(response.responseJSON.items[0]);
), it works perfectly and prints out the first item from the cart.

I've experimented with checking the object until it's no longer undefined using a while loop, and also attempted logging only after the page has fully loaded.

Just for clarity, here are the complete contents of my snippet:

var response = jQuery.getJSON('/cart.js');
$( document ).ready(function() {
    console.log(response.responseJSON.items[0]);
});

Any suggestions on how I can make this function directly within my snippet file?

EDIT: It's worth mentioning that the object is already parsed, so that isn't why I'm receiving an undefined message. I did try parsing it again just to see, but encountered another error.

EDIT 2: Here is the JSON data retrieved from the call:

{
  "readyState": 4,
  "responseText": "{\"token\":\"4472c3d68931e8fe2bff0afcca67a188\",\"note\":null,\"attributes\":{},\"original_total_price\":39800,\"total_price\":39800,\"total_discount\":0,\"total_weight\":0.0,\"item_count\":2,\"items\":[{\"id\":16640068878400,\"properties\":null,\"quantity\":2,\"variant_id\":16640068878400,\"key\":\"16640068878400:94cf8752e20f28a3f675ee10f8e5cc72\",\"title\":\"Compleu Abby - 60\",\"price\":19900,\"original_price\":19900,\"discounted_price\":19900,\"line_price\":398...

Answer №1

It is recommended to provide a callback function when making the request, as shown in the first example on the jQuery getJSON documentation, instead of assuming it's completed and utilizing the jqXHR object:

$(document).ready(function() {
  $.getJSON('/cart.js', function (data ) {
    console.log(data);
  });
});

If you want to learn more about asynchronous requests in Javascript, check out this helpful answer

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

Error: Attempting to assign a value to the property 'running' of an undefined variable

While working with Nuxt.js, I encountered an issue related to reading the running property of my client object. Here is the HTML code snippet: <b-button v-show="!(projectSelecter(project.ID)).isStarted" //this work just fine variant="success" c ...

How come I can successfully test the delete functionality in Postman, yet encounter issues when trying it in the browser?

While testing my HTTP delete request in Postman, everything ran smoothly. However, when I attempted to test it in the browser, I encountered a 'Cannot GET /account/delete/Julieth' error. To address this issue, I modified the method to GET, which ...

Guide for packaging the JavaScript loaded by the script manager from a CDN in Asp.Net

Currently, I am working on an asp.net application that utilizes a script manager in the master page. My goal is to load all scripts related to the script manager from a CDN, so I have set EnableCDN="true" in the script manager. <asp:ScriptManager runat ...

Error in ThreeJS: The constructor THREE.FaceNormalsHelper is not defined

I am currently studying a course on three.js and encountered an issue in Chrome version 79 while progressing through the material: "THREE.FaceNormalsHelper is not a constructor". The line causing trouble is as follows: normals = new THREE.FaceNormalsH ...

Transmit a Django model queryset to React via Ajax for seamless integration

I've been searching for information on this issue for quite some time now, but I haven't had any luck so far. The problem I'm facing is that I'm trying to display a list of Django models on a page using React, but my attempts to fetch t ...

Leveraging the node-jspdf library, jsPDF can be utilized on the server side in a

I am currently attempting to integrate jsPDF on the server side and use it for basic PDF generation (specifically outputting the text "Hello world!"). To view the generated PDF, visit localhost:8080. My first challenge is How can I include it / What step ...

Troubleshooting Three JS Projection Challenges

I have been attempting to find the centroid of a polygon in 3D space and then convert its vertices to 2D screen coordinates. Unfortunately, the code I currently have is not producing the desired results. I would greatly appreciate any assistance with this ...

Arrange the table by column following a service request

Is there a method to organize the table below once it has been loaded? I am utilizing Google API to retrieve distance matrix data, but I want the table to be sorted by distance. However, this sorting should take place after the Google service call is comp ...

What is the reason for this code failing to verify the authenticity of the passcode?

The validation process is not functioning properly and there seems to be a missing alert dialog box. I would like the passcode entered by the user to be compared with the constant "Pass". const Pass = '2207' function checkValidity() { con ...

Avoiding memory constraints when importing large JSON-encoded arrays

I am facing a challenge with a file that contains two JSON arrays; one with column names having 4 values and another array containing over 10,000 record values. While working with Symfony and Propel, I encountered an issue with json_decode leading to an " ...

Storing only the quotation mark character " in a C# string

Is there a way to receive JSON from a string and have it display double quotes instead of escaped sequences like \" in the code? Below is the code snippet that is causing the issue: internal static string ReturnRedditJsonPage(string subredditname) { ...

Folding without extending

My button has a div inside it with content. I've set it up so that when the div is clicked, the collapsed content expands. The hover effect changes color and pointer as expected. But for some reason, clicking on the div doesn't expand the content ...

Firing a personalized event using RxJS

I'm currently delving into the world of Reactive JS. While I have experience triggering custom events in JQuery like this: $(document).bind('eventbus', function(e, d) { console.log(d);}); $(document).trigger('eventbus', 'test ...

What is the best way to interpret a series of JSON-formatted dictionaries in Japanese without adding any additional characters?

Currently, I am extracting data from approximately 500 .js files, each following the same format: dict[0]=[{"some_key": "<b>名詞</b>", "another_key": "modification"}, {"some_key": "<b>名詞</b>", "another_key": "idea"}] This is ...

Extract the ID from the array, save it, and then delete it from the local storage

I am currently developing a mobile application using Angular, JavaScript, Ionic, and Cordova. Within one of my functions, I make use of an array called existingEntries, which is stored as a variable. categories: Array [276] [0...99] 0: Object id ...

JSON representation of 2 arrays

I am looking to combine 2 arrays in JSON format with keys and values. MyArray1 [ "Orange:10", "Orange:5", "Banana:20", "Apple:5" ] MyArray2 [ "Orange:5", "Banana:10", "Apple:15" ] MyJSON [ {"fruit": "Orange", "value": 15}, {"fruit": "Banana ...

Explain the concept of render hijacking in react technology

After learning about High Order Components (HOC), I came across the concept of render hijacking. Can someone please explain what exactly render hijacking entails? ...

Continuously waiting for JSON data in Objective-C until it receives a predetermined value

Currently, I am working on implementing an HTTP request using Objective-C with AFJSONRequestOperation for a mobile application. However, I'm facing a challenge in figuring out how to create a loop that will continue until a certain condition is met (s ...

Issues with passing information from a child component to a parent component in a

Currently, I am developing a guessing game that involves questions and selection logic embedded in a component known as Questions. However, I am facing issues with App not being able to read the Questions code correctly. My objective is to have the state i ...

Creating a Java class for retrieving the matching Gson JSON object

My JSON object contains the following data structure: { text : "Ed O'Kelley was the man who shot the man who shot Jesse James.", entities : [ ['T1', 'Person', [[0, 11]]], ['T2', 'Person&a ...