0

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.

Viral Patel
1,1001 gold badge8 silver badges17 bronze badges
asked Oct 20, 2021 at 11:48

1 Answer 1

1

first of all, Magento has five types of sessions :

Types of Magento 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.

enter image description here

answered Oct 21, 2021 at 10:27
1
  • Thanks for answer!! Commented Oct 21, 2021 at 10:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.