Hi I am working on shopify app.
Using the script_tag I added custom.js for shopify store front end.
When look in view source I can see custom to js added successfully
Basically I need a function or object if we have in shopify that i can use in my custom.js file remember I am not talking about theme file that return me complete info of cart like how many product added etc because that particular object I need to send with my ajax request to php file
Is there a way i can get cart detail in my app js file ?
2
Answers
Since you are using (.js) file you cannot directly access cart object. Instead you can use (.js.liquid) file type to access cart object. Both (.js) and (.js.liqud) works similarly. But by using (.js.liquid) file format you will be able to access all shopify objects.
Code…
For (.js.liquid) file type
refer cart object of shopify
But still if you want to access cart object in (.js) file you can access in json format by GET call.
Though Shopify offers a
.js.liquid
file format for the asset files, Shopify prevents accessing any information that might be dynamic (which would break the ability to cache the assets). So while it may be intuitive to try and use{{ cart | json }}
to dump the cart into the asset, carts are very dynamic and definitely not something you can liquid-dump into your code.Fortunately, there are other ways to get this info! If want to have the cart immediately on page load, you can use a snippet file to set a global javascript variable which would then be accessed by your asset file. However, that would only get the cart as it existed at page load, and if you’re using javascript to add/remove/modify items in the cart you’ll want to be able to get the current cart when needed.
Which brings us to using AJAX to hit your store’s
cart.js
endpoint. If you’re using a theme that has a full suite of Shopify helper functions, you might already have a function namedShopify.getCart
– this is a function that grabs the current cart from the above endpoint, and if you pass a function as a parameter into this function your function be called with the current cart object once the asynchronous call is complete.If your theme doesn’t have a built-in getCart function, it’s very easy to write your own. For example, if you are already using jQuery in your theme, you could make a function like this:
To get the cart and do something with it, simply make a function that does stuff with the cart data and use that function as a parameter in your getCart function.
Example:
Further, it’s worth noting that Shopify’s response object when you change or update the cart (through the
/cart/change.js
or/cart.update.js
endpoints, respectively) will pass the updated cart object to any success function that’s been supplied. So you could, for example, re-use your update function: