Magento 2: How to use Cookie?
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/
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
You can store cookie in js file using below method,
define([
'jquery',
'mage/cookies'
], function ($) {
$.cookie('cookiename', cookievalue);
});