0

I'm using the GET/cart.js call in an asset on my theme to get the cart contents in the form of a JSON object like this:

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

I then try to log to the console the contents of the object like this (within the same snippet file, right after making the call):

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

I get a TypeError: response.responseJSON is undefined within the console. If I try to log the same thing again within the console (console.log(response.responseJSON.items[0]);), it works and it prints the first item of the cart.

I tried checking the object until it isn't undefined anymore with a while loop and I also tried console logging only after the page fully loaded.

For sake of clarity, these are the full contents of my snippet:

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

How can I make this work straight from my snippet file?

EDIT: I should mention that the object is already parsed, so that's not the reason it's giving me undefined. I did try parsing it just for the sake of it, but it gave me another error.

EDIT 2: Here's the JSON I get 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\":39800,\"original_line_price\":39800,\"total_discount\":0,\"discounts\":[],\"sku\":\"2558\",\"grams\":0,\"vendor\":\"33 Aya\",\"taxable\":true,\"product_id\":1710662484032,\"gift_card\":false,\"url\":\"\\/products\\/compleu-abby?variant=16640068878400\",\"image\":\"https:\\/\\/cdn.shopify.com\\/s\\/files\\/1\\/0087\\/2500\\/4352\\/products\\/61_b38d4463-58b7-4569-bf0c-71b59fcb6e28.jpg?v=1544168500\",\"handle\":\"compleu-abby\",\"requires_shipping\":true,\"product_type\":\"\",\"product_title\":\"Compleu Abby\",\"product_description\":\"Compus din bluză dantelă cu tricot, eșarfă și pantalon tricot.\\n*eșarfa nu este inclusă în preț, este oferită cadou și poate varia în funcție de stocul disponibil\",\"variant_title\":\"60\",\"variant_options\":[\"60\"]}],\"requires_shipping\":true,\"currency\":\"RON\"}",
  "responseJSON": {
    "token": "4472c3d68931e8fe2bff0afcca67a188",
    "note": null,
    "attributes": {},
    "original_total_price": 39800,
    "total_price": 39800,
    "total_discount": 0,
    "total_weight": 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": 39800,
        "original_line_price": 39800,
        "total_discount": 0,
        "discounts": [],
        "sku": "2558",
        "grams": 0,
        "vendor": "33 Aya",
        "taxable": true,
        "product_id": 1710662484032,
        "gift_card": false,
        "url": "/products/compleu-abby?variant=16640068878400",
        "image": "https://cdn.shopify.com/s/files/1/0087/2500/4352/products/61_b38d4463-58b7-4569-bf0c-71b59fcb6e28.jpg?v=1544168500",
        "handle": "compleu-abby",
        "requires_shipping": true,
        "product_type": "",
        "product_title": "Compleu Abby",
        "product_description": "Compus din bluză dantelă cu tricot, eșarfă și pantalon tricot.\n*eșarfa nu este inclusă în preț, este oferită cadou și poate varia în funcție de stocul disponibil",
        "variant_title": "60",
        "variant_options": [
          "60"
        ]
      }
    ],
    "requires_shipping": true,
    "currency": "RON"
  },
  "status": 200,
  "statusText": "OK"
}
opportunityr
  • 173
  • 1
  • 12
  • A file ending on `.js` is a javascript source code file, so it will be read as text. What you're trying to do is read a `.json` file. So either convert cart.js to a cart.json file and write cart.json as valid json. Or else import the script file or parse it locally by changing your callback function. So we need to know what cart.js looks like. – Shilly Dec 11 '18 at 09:59
  • @Shilly, the [documentation page on Shopify Ajax API](https://help.shopify.com/en/themes/development/getting-started/using-ajax-api) says that even though all URLs end with `.js`, the response is a JSON object. I added the object I get in the post anyway. – opportunityr Dec 11 '18 at 10:09
  • 1
    You're not using a callback. Use a callback and then your data is available as `response.items[0]`. AS written, you log the entire request before it resolves, hence you're looking for a responseJSON property that does not exist yet. Just follow the sample code from the docs you linked. – Shilly Dec 11 '18 at 10:18

1 Answers1

1

You should pass a callback when making the request (see the first example in the jQuery getJSON docs) rather than assuming it's completed and using the jqXHR object:

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

For more info on async requests in Javascript, see this excellent answer

caffeinated.tech
  • 5,846
  • 19
  • 36