How to set data into the session with ajax Magento 2, I want to store price into the session with ajax for when the site is refreshed price gets from the session, not from the database.
1 Answer 1
first of all, Magento has five types of sessions :
below is an example of a controller which works when an ajax requests, in that controller I have applied the logic for storing data into the customer session, or if you want any other, please add the comment, i will do so,
Now please find the code below for the controller for the customer session saving:
<?php
 namespace Vendor\Module\Controller\Index;
 use Magento\Customer\Model\Session;
 use Magento\Framework\App\ActionInterface;
 use Magento\Framework\App\RequestInterface;
 use Magento\Framework\Controller\Result\JsonFactory;
 use Magento\Framework\Controller\ResultFactory;
 class Save implements ActionInterface
 {
public $request;
public $session;
public $jsonFactory;
public $resultFactory;
public function __construct(
 Session $session,
 RequestInterface $request,
 JsonFactory $jsonFactory,
 ResultFactory $resultFactory
) {
 $this->session = $session;
 $this->request = $request;
 $this->jsonFactory = $jsonFactory;
 $this->resultFactory = $resultFactory;
}
public function execute()
{
 $customerSession = $this->session->getData();
 $this->session->setSampleName('Mona Lisa');
 $getNames = $this->session->getSampleName();
 $data = $this->session->getData();
 $redirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
 $params = $this->request->getParams();
 return $redirect->setPath('rma/rma/request');
}
}
And here you will find the data in run time when I'm debugging that it is being saved into the customer session.