0

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!!

Jafar Pinjar
  • 1,929
  • 7
  • 64
  • 139
  • what about the local storage? cart items/info is normally available in it – SantiBM Oct 28 '20 at 13:07
  • @SantiBM, yes, this is one event i mentioned above, like that I have to make for all major events in magento2(order. delete cart, invoice, shipment, customer_login) etc.. – Jafar Pinjar Oct 28 '20 at 13:32
  • @SantiBM, please update your answer – Jafar Pinjar Oct 29 '20 at 12:45
  • hi! try this: https://magento.stackexchange.com/questions/301886/magento2-how-to-get-cart-items-collection-on-product-view-page I'm not sure why you need to use an observer if your goal is to have the data in the console – SantiBM Oct 29 '20 at 17:26
  • @SantiBM, bcz i have to send the info to third party tool using javascript. so I am sending data from all the events, that i can get it in phtml, a javascript function is written in phtml to take this data recieved from observer. \ – Jafar Pinjar Oct 30 '20 at 06:37
  • @SantiBM, The suggested link is not relevant to my requirement. – Jafar Pinjar Oct 30 '20 at 06:38
  • in phtml have you first check it will give the data what you set from observer? – Dhiren Vasoya Nov 02 '20 at 10:14
  • Yes I am getting data in phtml which is set in observer, but the javascript written in phtml not working, not even console.log – Jafar Pinjar Nov 02 '20 at 10:46

1 Answers1

1

define same observer into below event.

   <event name="controller_action_predispatch_catalog_product_view">
       <observer name="send_data2" instance="Vendorename\Modulename\Observer\Yourfilename" />
   </event>
    <event name="checkout_cart_product_add_after">
       <observer name="send_data1" instance="Vendorename\Modulename\Observer\Yourfilename" />
   </event>

Add into your Observer file

protected $resultPageFactory;

public function __construct( ............................................................. \Magento\Framework\View\Result\PageFactory $resultPageFactory, .............................................................

) { ................................................ $this->resultPageFactory = $resultPageFactory; ............................................... } public function execute(\Magento\Framework\Event\Observer $observer) { ob_start(); $rowData = "your custom data"; // you can add object json array any kind of data $resultPage = $this->resultPageFactory->create();

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager-&gt;get('\Magento\Checkout\Model\Cart');

// retrieve quote items collection
$itemsCollection = $cart-&gt;getQuote()-&gt;getItemsCollection();

// get array of all items what can be display directly
$itemsVisible = $cart-&gt;getQuote()-&gt;getAllVisibleItems();

$data = [];
$x = 0;
foreach($itemsVisible as $item) {
    $data[$x]['name'] = $item-&gt;getName();
    $data[$x]['sku'] = $item-&gt;getSku();
    $data[$x]['qty'] = $item-&gt;getQty();
    $x++;
  }
$phtml_data = json_encode($data);

$block = $resultPage-&gt;getLayout()
        -&gt;createBlock(\Vendorname\Modulename\Block\CustomBlock::class)
        -&gt;setData('customdata', $phtml_data)
        -&gt;setTemplate(&quot;Vendorname_Modulename::customdata.phtml&quot;)-&gt;toHtml();
echo $block;

}

Add into your phtml file

<?php
$data = $block->getData('customdata');
print_r($data);
?>

<script type="text/javascript"> console.log("<?php echo $data; ?>"); </script>

I Hope This Helps You.

Msquare
  • 9,063
  • 7
  • 25
  • 63