1

Given an object:

var object = {
        "key1" : Math.random()*10000000000000000,
        "key2" : "value",
        "key3" : "value",
    }

How can I store this in a browser cookie, when someone fills out a form with corresponding values? When the user comes back to the page to fill out the form, the values should populate the form from the cookie.

Matt
  • 1,561
  • 5
  • 26
  • 61
  • 6
    `JSON.stringify()`/`JSON.parse()` – Jason P Jan 14 '14 at 20:10
  • possible duplicate of [Pure Javascript - store object in cookie](http://stackoverflow.com/questions/11344531/pure-javascript-store-object-in-cookie) – Felix Kling Jan 14 '14 at 20:11
  • and [can we assign object into cookie in javascript?](http://stackoverflow.com/q/1276238/218196) – Felix Kling Jan 14 '14 at 20:12
  • I get a JSON object using `var formCookie = JSON.stringify(object);`, so the question is how to store that into a cookie, and then retrieve it and parse. – Matt Jan 14 '14 at 21:08
  • 1
    `JSON.stringify()` gives you a json _string_. There is no such thing as a "json object". Since you now have a string, storing the value in a cookie should be trivial. Your favorite search engine should be able to direct you to hundreds of examples. – Jason P Jan 15 '14 at 01:42

3 Answers3

1

convert your object/array to json string. You can set cookie like :

  var object = {
    "key1" : Math.random()*10000000000000000,
    "key2" : "value",
    "key3" : "value",
    }

 let objectString = JSON.stringify(object);
document.cookie = "myobject=" + objectString + "; expires="+ (new Date()).toDateString();

The above cookie expires today. You can set other optional value as all.

To retrieve a cookie set earlier :

  let cookies = document.cookie;
   console.log(cookies);
infomasud
  • 2,263
  • 1
  • 18
  • 12
0

Extending the answers already given (comments and custom JS method)... i wanted to place this in a working example... So here goes...

First of, using JSON allows you to easily convert a object to and from JSON without having to use your own methods.. It is the most common way and a well known standard these days.. So a majority of languages have support for JSON..

Extending the example provided by subas chandran...

var object={name : username.value, email : email.value, gender : gender.value};
var stringObj=JSON.stringify(object);

as seen here http://jsfiddle.net/LLujbb2h/ makes its easy to use, and your not restricted if you want to deal with strings / arrays and objects.. You simply hand it the main object and it does all the work for you... So why re-invent the wheel??

Using the non JSON method as show here http://jsfiddle.net/1bf4dg8o/ has a lot of problems like dealing with the object once you read it back from the cookie.. Its just a string... if say for example you put :: in your name/email/gender.. This would break the custom syntax... I would avoid this method at all costs!

Simply, test the first fiddle i have created and you'll see its alot easier to deal with...

Also use the inspector on your browser to view the cookie, as this will help with debugging..

EDIT - Showing how to read back the cookie into a JS object http://jsfiddle.net/LLujbb2h/2/

Angry 84
  • 2,935
  • 1
  • 25
  • 24
-1
var saveButton=document.getElementById("save");
var username=document.getElementById("Name");
var email=document.getElementById("Email");
var gender=document.getElementById("Gender");
function setCookie(value, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = "Username"+ "=" + value + "; " + expires;
    if(document.cookie)
        return true;
}
function objToString (obj) {
    var str = '';
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            str += p + '::' + obj[p] + '\n';
        }
    }
    return str;
}
saveButton.onclick=function () {
    // body...
    var object={name : username.value, email : email.value, gender : gender.value};
    var stringObj=objToString(object);
    alert(stringObj);
    if(setCookie(stringObj,1))
        alert("cookie set");
}; 
subas chandran
  • 13
  • 1
  • 1
  • 5
  • 2
    way to complex for a simple task, think you might have confused the OP instead of helping.. A JSON string is all that is needed... – Angry 84 Apr 07 '15 at 07:05
  • Sorry but had to down vote as i see a few problems here, Firstly the above code does not work straight of the bat.. You need to remove the newline. Second, in the case of a name/email or any string.. This will not be easy to convert back to a object without using a regex type expression.. Also if i was to simply add :: into a string, this would break the script further more.. I only comment on this as people who google for answers should have the best direction to save them time. – Angry 84 Apr 07 '15 at 11:08