ramirez ramirez - 2 months ago 12
JSON Question

How to set variable in JSON cookie?

I'm using js.cookie.js Github and trying to set a JSON cookie.
In documentation of js.cookie.js mentioned that if you want set a JSON cookie you must do like this:

Cookies.set('name', { foo: 'bar' });


so the cookie data will be like below if you call
Cookies.getJSON('name');
:

{ foo: 'bar' }


Now my question is how to set
foo
from a javascript variable. I tried this but was not useful:

var myVar = 'foo';
Cookies.set('name', { myVar: 'bar' });


the result was
{ myVar: 'bar' }
and not
{ foo: 'bar' }


My JSFIDDLE.COM test: https://jsfiddle.net/nz2ur613/

Answer
document.onload = Do();
   function Do() {
   var myvar = 'foo';
   var obj = {} ;
   obj[myvar] = 'bar';
   Cookies.set('name', obj);
   alert(Cookies.get('name'));
 }

I created an object and then set it to cookie.

Try this one. It will work

Demo : https://jsfiddle.net/snuny9om/

Comments