1

I have created a custom js file in my custom module.

app\code\Vendor\Module\view\frontend\layout\default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
     <script src="Vendor_Module::js/test.js"/>
 </head> 

app\code\Vendor\Module\view\frontend\web\js\test.js

function Test(json){
 console.log('Test Web',json);
}

Then used add to cart event.

app\code\Vednor\Module\etc\events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
  <event name="checkout_cart_product_add_after">
    <observer name="vendor_module_observer_checkoutcartproductaddafter" 
      instance="Vendor\Module\Observer\Checkoutcartproductaddafter" />
  </event>
 </config>

Vendor\Module\Observer\Checkoutcartproductaddafter.php

class Checkoutcartproductaddafter implements \Magento\Framework\Event\ObserverInterface
{

private $image; public function __construct( \Magento\Catalog\Helper\Image $image { $this->image = $image; }

public function execute(\Magento\Framework\Event\Observer $observer) { $event = $observer->getEvent();

$eventData = $event-&gt;getData('quote_item');
$item = ($eventData-&gt;getParentItem() ? $eventData-&gt;getParentItem() : $eventData);
$product = $item-&gt;getProduct();
$productId = $product-&gt;getId();
$imageHelper = $this-&gt;image;
$productImageUrl = $imageHelper-&gt;init($product, 'product_page_image_large')-&gt;getUrl();
$OrgPrice = (float)$product-&gt;getPrice();

$prepareJson = array(
        'event_name' =&gt; 'Added To Cart',
        'event_data' =&gt; array(
            'productId' =&gt; $productId,
            'productName' =&gt; $product-&gt;getName(),
            'productDescription' =&gt; $product-&gt;getDescription(),
            'productShortDescription' =&gt; $product-&gt;getShortDescription(),
            'productSku' =&gt; $product-&gt;getSku(),
            'productUrl' =&gt; $product-&gt;getProductUrl(),
            'productImage' =&gt; $productImageUrl,
            'productOriginalPrice' =&gt; $OrgPrice,
            'productQty' =&gt; (float)$eventData-&gt;getQty(),
    )
);

$json = json_encode($prepareJson);
echo '&lt;script type=&quot;text/javascript&quot;&gt;
        require([&quot;jquery&quot;, &quot;jquery/ui&quot;], function($){ 
        $(document).ready(function(){
            console.log(&quot;inside observer&quot;);
            Test('.$json.')
        });
     });&lt;/script&gt;';
return $this;
}

}

So whenever Add to cart is happened, I am trying to call my js function. but which is not happening.

Same I have to achieve for all the main events in magento. so created the common js function and trying to send the data in each observers.

In the above example i have mentioned Add to cart event to see if that works.

Can anyone help me with this. Thanks!!

Manjunath
  • 177
  • 7
  • 28
  • maybe this can guide you a little to achieve the same. https://magento.stackexchange.com/a/239524/51548 – Rizwan Khan Oct 07 '20 at 05:35
  • @RizwanKhan, I am trying to implement it for all the major events, so the link you shared may work for Add to cart. so instead of writing the mixins for each events, can we do it via observer? Any chances there] – Manjunath Oct 07 '20 at 06:18
  • @RizwanKhan, if any other approach is there, pls suggest me – Manjunath Oct 07 '20 at 13:16
  • There are various ways that the backend and fronted are kept in sync. The details depend on the implementation. E.g. customerData can manage data in the browser's local storage, and that is how, e.g., the minicart is updated asynchronously, using knockout subscribers. You could use that model for additional features, but they will require a specific approach to each event that hooks in to how the event is triggered in the browser and handled in the backend. – jiheison Oct 11 '20 at 16:02
  • @jiheison, please update me as answer how this can be achieved. – Manjunath Oct 12 '20 at 05:33
  • How customerData works is detailed here: https://magento.stackexchange.com/a/143381/66951 . Basically, you would hook a custom customerData "section" to your event's action (e.g. adding an item to the cart), and then trigger the customerData reload either when the page reloads or an AJAX query completes. When the customerData reload completes the knockout subscriber triggers your custom JS. No backend observer is required, because your sections.xml will trigger the backend action based on the request path. – jiheison Oct 12 '20 at 05:51

1 Answers1

0

I would do this way:

In your observer add the data to session.

use Magento\Customer\Model\Session
$this->customerSession->setMyData($json)

And in my default.xml

    <referenceContainer name="before.body.end">
        <block class="NameSpace\ModuleName\View\Element\Template" name="my.before.end" template="NameSpace_ModuleName::before-body-end.phtml" />
    </referenceContainer>

And now in NameSpace\ModuleName\View\Element\Template.php class:

public function getJsonDataFromSession()
{
    //Magento\Customer\Model\Session
    return $this->customerSession->getMyData();
}

and in before-body-end.phtml

<?php $jsonData = $this->getJsonDataFromSession()?>
<?php if ($jsonData):?>
    //call your script
<?php endif;?>

Important

Have some logic to clear your session data to handle browser refresh or something similar.

Not tested but should work. Good luck.

UPDATE

When a product is added to the cart the local storage information is updated and you can subscribe to a knockout observable.

require(['Magento_Customer/js/customer-data'], function (customerData) {
    var cart = customerData.get('cart');
    var count = cart().summary_count;
    cart.subscribe(function () {
        if (cart().summary_count !== count) {
            count = cart().summary_count;
            // call your code here
            console.log('Number of items in cart is now: ' + count);
        }
    });
});
Adarsh Khatri
  • 8,360
  • 2
  • 25
  • 58