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->getData('quote_item');
    $item = ($eventData->getParentItem() ? $eventData->getParentItem() : $eventData);
    $product = $item->getProduct();
    $productId = $product->getId();
    $imageHelper = $this->image;
    $productImageUrl = $imageHelper->init($product, 'product_page_image_large')->getUrl();
    $OrgPrice = (float)$product->getPrice();

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

    $json = json_encode($prepareJson);
    echo '<script type="text/javascript">
            require(["jquery", "jquery/ui"], function($){ 
            $(document).ready(function(){
                console.log("inside observer");
                Test('.$json.')
            });
         });</script>';
    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!!

  • maybe this can guide you a little to achieve the same. magento.stackexchange.com/a/239524/51548 – Rizwan Khan Oct 7 at 5: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 7 at 6:18
  • @RizwanKhan, if any other approach is there, pls suggest me – Manjunath Oct 7 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 at 16:02
  • @jiheison, please update me as answer how this can be achieved. – Manjunath Oct 12 at 5:33
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);
        }
    });
});
| improve this answer | |
  • how to clear the session. if page refreshed. any way to handle it? – Manjunath Oct 8 at 6:28
  • also this is not working for add to cart, my function is not being called – Manjunath Oct 9 at 14:05
  • session data will get only when page is refreshed, not upon add to cart, because that's a ajax call. – Manjunath Oct 9 at 14:10
  • You can use knockout. – Adarsh Khatri Oct 9 at 14:27
  • possible to update as answer pls? @Adarsh. – Manjunath Oct 10 at 1:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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