ramirez ramirez - 1 year ago 78
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

{ foo: 'bar' }

Now my question is how to set
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 Source
document.onload = Do();
   function Do() {
   var myvar = 'foo';
   var obj = {} ;
   obj[myvar] = 'bar';
   Cookies.set('name', obj);

I created an object and then set it to cookie.

Try this one. It will work

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download