youYou can use ajax from Phtml file to the controllersession on your observer to get JSON Data. you controller should returnstore JSON response that you are getting from API.
Code for controller returning JSON response given belowLater on the phtml, you get this session data from a Block file.
you can use below code in your observer to store data in the customer session
observer code
namespace Company\MyModule\Controller\Ajax;
<?php
\Magento\Framework\Controller\Result\JsonFactorynamespace $resultJsonFactory,Vendor\Module\Observer\Customer;
class IndexAuthenticated extendsimplements \Magento\Framework\App\Action\Action
ObserverInterface {
............
private $resultJsonFactory; protected $_customerSession;
............
public function __construct(
............
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory, \Magento\Customer\Model\Session $customerSession
............
) {
............
$this->resultJsonFactory $this->_customerSession = $resultJsonFactory;$customerSession;
............
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$result = ............
$this->resultJsonFactory>_customerSession->create>setMyVar1('my var 1 data');
$jsonResponse = [ $this->_customerSession->setMyVar2('my var 2 data');
............
'Field_1'return $this;
=> "value 1" }
}
Block class code (assumed your Block class file is Vendor\Module\Block\Myblock.php)
<?php
namespace Vendor\Module\Block;
class Myblock extends \Magento\Framework\View\Element\Template
{
private $customerSession;
private $storeManager;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Customer\Model\Session $customerSession,
'Field_2' => "value 2" \Magento\Store\Model\StoreManagerInterface $storeManager
];) {
$this->customerSession = $customerSession;
$this->_storeManager = $storeManager;
parent::__construct($context);
}
public function getMyVarOne()
{
return $result$this->setData>getCustomerSession($jsonResponse)->getMyVar1();
}
public function getCustomerSession()
{
return $this->customerSession;
}
}
Phtml File Code (assumed your phtml file is Vendor/Module/view/frontend/templates/myblock.phtml)
<?php echo $block->getMyVarOne(); ?>
Please Note: since you will store JSON data, you may need to use json_encode and json_decode to store and parse data.