Magento 2 – Get Product Details in JS on Add to Cart Click

addtocartmagento2requirejs

I know how to extend the catalogAddToCart function and already successfully fired my codes when I go into product detail page and press Add To Cart button. But I still has a problem: how can I get the product details on the product to be added into cart, like SKU? Currently I use global variable to get it like this:

On app/code/Vendor/ModuleName/view/template/frontend/templates/cart/addtocart.phtml

<script type="text/x-magento-init">
    {
        "#product_addtocart_form": {
            "MyAddToCart": ""
        }
    }
</script>
<script>
    var product_sku = '<?php echo $block->getProduct()->getSku(); ?>';
</script>

Then on app/code/Vendor/ModuleName/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            'MyAddToCart': 'Vendor_ModuleName/js/MyAddToCart'
        }
    }
};

Finally on app/code/Vendor/ModuleName/view/frontend/web/js/MyAddToCart.js

define([
    'jquery',
    'jquery/ui',
    'Magento_Catalog/js/catalog-add-to-cart'
], function($){
    "use strict";
    $.widget('Vendor.MyAddToCart', $.mage.catalogAddToCart, {
        submitForm: function(form) {
            var productSku = product_sku;
            //Rest of codes
        }
    });
    return $.Vendor.MyAddToCart;
});

I can get the correct SKU, but how about other product attributes? Seems using global variable method is not so good in this case. Is there any internal methods to get the product attributes inside MyAddToCart without using global variable?

Best Answer

Your close, you can pass PHP to the JS inside the x-magento-init command:

<script type="text/x-magento-init">
    {
        "#product_addtocart_form": {
            "MyAddToCart": {
                "sku": "<?php echo $block->getProduct()->getSku(); ?>"
            }
        }
    }
</script>

To access it in your JS you need to add the following:

return function (config) {
    var sku = config.sku;
}

I don't have time to test it so let me know if you have any issues.

Related Topic