9

How can we use cookie in magento 2 to store data..

i'm trying to store data in cookie, on vendor/magento/module-checkout/view/frontend/web/js/model/resource-url-manager.js to store selected estimated shipping method,

18

app/code/Custom/Module/view/frontend/templates/sample.phtml

<script type="text/javascript">
    require([
        'jquery',
        'jquery/jquery.cookie'
    ], function ($) {
        $(document).ready(function () {

            var check_cookie = $.cookie('foo'); // Get Cookie Value
            var date = new Date();
            var minutes = 60;
            date.setTime(date.getTime() + (minutes * 60 * 1000));
            $.cookie('foo', '', {path: '/', expires: -1}); // Expire Cookie
            $.cookie('foo', 'bar', {expires: date}); // Set Cookie Expiry Time
            $.cookie('foo', 'setvalue'); // Set Cookie Value
        });// You need to add ); to correct burg in your code
    }); 
</script>

Helpful Article on PHP Side: https://webkul.com/blog/set-get-data-cookie-magento2/

1
  • 1
    As @rakesh-jesadiya states below, you should be using mage/cookie for most use cases. Doing so will automatically use the cookie config for the Magento store without needing to explicitly define them with jquery/jquery.cookie. – Pmclain Sep 17 '17 at 21:25
11

In the target.phtml, add js codes like below.

Set the cookies

<script>
    require([
        'jquery',
        'jquery/jquery.cookie'
    ], function ($) {
       $.cookie('cookie_name', 'value', { expires: 7, path: '/' });//Set the cookies
    });
</script>

jquery/jquery.cookie is defined in the file lib/web/jquery/jquery.cookie.js. Below is parameter description.

expires

Define when the cookie will be removed. Value must be a Number which will be interpreted as days from time of creation or a Date instance. If omitted, the cookie becomes a session cookie.

path

If you want get the value from another page, notice the path setting { path: '/' }.

Because cookies are only accessible to the specified path and any subpaths , more discussion about this you could see here Cookie path and its accessibility to subfolder pages.


Get the cookies

<script>
    require([
        'jquery',
        'jquery/jquery.cookie'
    ], function ($) {
        var temp = $.cookie('cookie_name');//Get the cookies
    });
</script>

Supplement

mage/cookies

mage/cookies could replace jquery/jquery.cookie, it did some initialization work which you could see it in the file lib/web/mage/cookies.js.

Usage: $.mage.cookies.set('name', 'value', {lifetime: -1});

use cookie in PHP

You could use the php class in this answer https://magento.stackexchange.com/a/100142/44237

6
  • how to use this cookies on observer or controller – Sarvesh Tiwari Jul 9 '18 at 15:29
  • I try with above code but i am not getting cookie value in another page. – Chirag Patel Oct 12 '18 at 8:48
  • Also i was checked in console but i can't find there. – Chirag Patel Oct 12 '18 at 8:48
  • @ChiragPatel Do you set the path right? Cookies are only accessible to the specified path and any subpaths. – Key Shang Oct 12 '18 at 9:14
  • @KeyShang Thanks! i solved my problem there is a problem with my code. – Chirag Patel Oct 12 '18 at 10:06
10

You can store cookie in js file using below method,

define([
    'jquery',
    'mage/cookies'
], function ($) {
    $.cookie('cookiename', cookievalue);
});
9
  • mage/cookies is for Magento 1? – Jackson Mar 8 '17 at 7:29
  • 1
    @AnkitShah mage/cookies is also working in magento 2. – Rakesh Jesadiya Mar 8 '17 at 9:05
  • Any idea how to set an expiration date using this method @RakeshJesadiya? – Ben Crook Oct 3 '17 at 12:58
  • @BenCrook, $.cookie('foo', '', {path: '/', expires: -1}); is not working for you? – Rakesh Jesadiya Oct 3 '17 at 12:59
  • 1
    Turns out it expires with the user's session by default which is what I needed. Related question, is there any difference between $.cookie() and $.mage.cookies.set()? – Ben Crook Oct 3 '17 at 13:16
0

use the below to store data inside cookie. Here is the code,

<script>
require([
    'jquery',
    'jquery/jquery.cookie',
    'domReady!'
], function($) {
  var data = "store my data";
  $.cookie('my_data', data );
  console.log($.cookie('my_data'));
});
</script>
0

Just in case you need to open or not a modal after the cookie check:

 require(
    [
        'jquery',
        'Magento_Ui/js/modal/modal',
        'jquery/jquery.cookie'
    ],

this is the correct order otherwise the modal will not work

0

How to add when i open a report in magento. I see the ajax url loading to display content into grid. How to check ajax url loading and add cookie for that ajax? or How to disable ajax loading for ui component grid listing in magento 2?

1
  • you can create a separate question for your query.. no one will identify your question here.. – Yogesh Jun 12 '20 at 14:19
0

For those of you struggling with setting php cookie and accessing it in js:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $metadata = $objectManager->get('Magento\Framework\Stdlib\Cookie\CookieMetadataFactory') ->createPublicCookieMetadata() ->setPath('/') ->setHttpOnly(false);

$objectManager->get('Magento\Framework\Stdlib\CookieManagerInterface')->setPublicCookie('cookieexample','Error', $metadata);

The result was a cookie with the domain .example.shop.com

When I set an empty domain as parameter $.cookie('foo', 'bar', { domain: '' });

I get a cookie with the domain example.shop.com and everything works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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