I am trying to send Observer info into the block file. used the add to cart event as like below.
app/code/Vendor/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="event_observer_checkoutcartproductaddafterwe" instance="Vendor\Module\Observer\Checkoutcartproductaddafter" />
</event>
</config>
Then
app/code/Vendor/Module/Observer/Checkoutcartproductaddafter.php
<?php
namespace Vendor\Module\Observer;
class Checkoutcartproductaddafter implements \Magento\Framework\Event\ObserverInterface
{
protected $layout;
public function __construct(
\Magento\Framework\View\Layout $layout)
{
$this->layout = $layout;
}
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();
$prepareJson = array(
'Added To Cart' => array(
'productId' => $productId,
'productName' => $product->getName(),
)
);
$block = $this->layout->createBlock('Vendor\Module\Block\Index\Index')->setTemplate('Vendor_Module::before-body-end.phtml')
->setObserverData($prepareJson)
->toHtml();
}
}
Vendor/Module/view/frontend/templates/before-body-end.phtml
<?php
$jsonData = $block->getObserverData();
?>
<script id='test_script' type='text/javascript'>
console.log('inside');
var data = '<?php echo $jsonData; ?>';
console.log('--data--',data);
</script>
From the above code I am able to pass the observer data into the phtml file, but I am trying to print the received info into the browser console.
Once printed in browser i have to send to a third party tool using javascript function.
The problem is whatever js is written That's not working. Please help me how can we achieve this. Thanks in Advance!!