3

I am trying to get the cart items in phtml file (product detail page) using jquery script. Here is the script:

require([ 'jquery', 'jquery/ui'], function($,item){
item = require('Magento_Customer/js/customer-data').get('cart')().items; 
console.log(item.length);
});

It did not load customer data all the time. I need this to get the item count when a product is added or deleted from the mini cart dynamically using ajax cart. On firefox, its works but fails in chrome browser. I don't know how to initialize the requirement ('Magento_Customer/js/customer data) early so that it works well for all cases. Please help or provide other solutions to get the cart item dynamically using jquery

2 Answers 2

0

Try below code:

define(['jquery', 'jquery/ui', 'Magento_Customer/js/customer-data'], 
function($,item,customerData){
    var summaryCount = customerData.get('cart')().summary_count; 
    var item = customerData.get('cart')().items;
    console.log(summary_count);
    console.log(item.length);
});
2
  • it gives define error, as i have to used in phtml file,instead of define i changed to require, but same issue..sayd summary_count undefine Commented Feb 3, 2020 at 2:57
  • Uncaught TypeError: Cannot read property 'length' of undefined Uncaught TypeError: Cannot read property 'summary_count' of undefined Commented Feb 3, 2020 at 3:07
0

you have to add a sequence into your module.xml

etc/module.xml

<?xml version="1.0"?>
<config>
    <module name="Module_Name">
        <sequence>
            <module name="Magento_Customer"/>
        </sequence>
    </module>
</config>
2
  • It's not right. Every JS module in the system can be loaded on demand, so sequence doesn't matter for frontend. Commented Apr 3, 2020 at 16:39
  • Welcome to stackexchange! Commented Apr 3, 2020 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.