khush123456
khush123456

Reputation: 65

Creating a javascript cookie

I am attempting to create a cookie. I suspect that my cookie isnt saving or being retrieved properly. What am I doing wrong?

I tried 2 methods to save this cookie:

  1. Cookie gets saved in this function:

    function(config) {
        var config_copy = JSON.parse(JSON.stringify(config));
        setCookie('key',config_copy);
    }
    
  2. Use setCookie();

    function(config) {
        var config_copy = JSON.parse(JSON.stringify(config));
        setCookie();
    }
    

Then trigger this function:

function setCookie(key,config_copy){
    document.cookie = key + "=" + config_copy;
    console.log("cookie saved");
    console.log(config_copy);
}

console.log(config_copy); returns undefined in the console.

How would I correctly save the value of config_copy into a JavaScript cookie?

Upvotes: 1

Views: 148

Answers (4)

user4639281
user4639281

Reputation:

Document.cookie only accepts primitive values, if you pass an object it calls Object.toString() which returns [ object Object ].

You have too options for storing an object in cookie form.

  1. Multiple cookies from an object's properties

    If you want to make a cookie out of each property of an object, you have to loop through the object and create a cookie out of each property.

    var saveConfig = function(config) {
        var cookies = [];
        for(var i in config)
            cookies.push(document.cookie = i + '=' + config[i]);
        return cookies;
    }
    saveConfig({hello: 'world', foo: 'bar'});
    console.log(document.cookie);
    
    Outputs: hello=world; foo=bar;
    

  2. One cookie from an object converted to a string

    You can convert the object to a string and store it in one cookie using JSON.stringify().

    var saveConfig = function(config) {
        return document.cookie = 'config=' + JSON.stringify(config);
    }
    saveConfig({hello: 'world', foo: 'bar'});
    console.log(document.cookie);
    
    Outputs: config={"hello":"world","foo":"bar"};
    

Upvotes: 1

Barmar
Barmar

Reputation: 782693

JSON.parse() returns an object, not a JSON string. You should put the JSON string into the cookie, not the result of JSON.parse.

function saveConfig(config) {
    var config_copy = JSON.stringify(config);
    setCookie("key", config_copy);
}

Otherwise, you'll just set the cookie to [Object object].

Upvotes: 1

Scott
Scott

Reputation: 25

You need to pass your variables to setCookie() in order for the function to use them.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Calling_functions

Upvotes: 0

lem2802
lem2802

Reputation: 1162

In your second "option" you have to send a value for the parameters like this:

function(config) {
    var config_copy = JSON.parse(JSON.stringify(config));
    setCookie("key", config_copy);
}

if you call it without the parameters, they will have an undefined value

Upvotes: 0

Related Questions