Skip to content

How to call javascript function from Observer file in Magento 2

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

appcodeVendorModuleviewfrontendlayoutdefault.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> 

appcodeVendorModuleviewfrontendwebjstest.js

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

Then used add to cart event.

appcodeVednorModuleetcevents.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="VendorModuleObserverCheckoutcartproductaddafter" />
  </event>
 </config>

VendorModuleObserverCheckoutcartproductaddafter.php

class Checkoutcartproductaddafter implements MagentoFrameworkEventObserverInterface
{

private $image;
public function __construct(
    MagentoCatalogHelperImage $image
{
    $this->image = $image;
}

public function execute(MagentoFrameworkEventObserver $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!!