I’m using the jquery cookie plugin to store an object in a cookie. The object contains various properties which store information about the visitor to the site. Is there a way to retrieve the cookie and access these properties? Or do I have to store each piece of data in a separate cookie? Here’s my code:
c.consumerID = data.LoginConsumer.ConsumerId;
c.surveyCount = data.LoginConsumer.SurveyCnt;
c.vehicleCount = data.LoginConsumer.VehicleCnt;
c.sid = data.LoginConsumer.SurveyId;
c.aid = data.LoginConsumer.ActivityId;
c.loggedIn = true;
$j.cookie('consumerCookie', c, { path: '/' });
console.log($j.cookie()); //WANT TO RETRIEVE THE VALUES OF THE OBJECT IN THE COOKIE HERE, LIKE c.sid
Cookies store strings, so if you want to store six properties from an object, you will either have to store each property individually as it’s own string and give each a name or you will need to combine all the property values into one string.
You could use a JSON library to stringify the whole object and then read the JSON back in when reading the cookie. For example to store all the data in the cookie, it would work like this:
And, to read it back in, you could do this:
Note: it doesn’t appear that jQuery has stringify built-in so if you go the stringify route, for older browsers you will have to make sure that there is a JSON.stringify capability.