0

I want to save string from js file in session because i want to use that value in controller. How to save value in session from js file.

I want to save one string which size is 200kb. so i want to save it in session.

Is there any other way to pass value from js to controller then please mention in answer.

I want to passed value without using ajax. so how to set value in session.

6
  • 1
    without ajax it is not possible. you can you cookie instead of session Jun 28, 2017 at 4:39
  • 1
    is it possible to store 200kb data in cookie? Jun 28, 2017 at 4:43
  • you should use ajax call to save it in session Jun 28, 2017 at 5:15
  • 1
    @MineshPatel Read my question.... I mention in the question that i don't want to use ajax Jun 28, 2017 at 5:23

1 Answer 1

0

You can just set below code in your phtml file to use ajax, You have to change your customurl in below code,

<script type="text/javascript">
    require(["jquery"],function($) {
        $(document).ready(function() {
            var customurl = "<?php echo $this->getUrl().'frontname/index/index'?>";
            $.ajax({
                url: customurl,
                type: 'POST',
                dataType: 'json',
                data: {
                    customdata1: 'test1',
                    customdata2: 'test2',
                },
            complete: function(response) {             
                country = response.responseJSON.default_country;
                state = response.responseJSON.state;         
                console.log(state+' '+country);   
                },
                error: function (xhr, status, errorThrown) {
                    console.log('Error happens. Try again.');
                }
            });
        });
    });
</script>

inside your controller file execute() method,

<?php
 use Magento\Framework\Controller\ResultFactory;
 public function execute()
    {
        $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE);

        $response = $this->resultFactory->create(ResultFactory::TYPE_RAW);
        $response->setHeader('Content-type', 'text/plain');
        $country = 'india';
        $state = 'gujarat';
        $response->setContents(
            $this->_jsonHelper->jsonEncode(
                [
                    'default_country' => $country,
                    'state' => $state,
                ]
            )
        );
        return $response;
    } 

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.