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.

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

1
  • Thanks for answer!!
    – NoOn
    Oct 21, 2021 at 10:29

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.