maudulus
maudulus

Reputation: 11035

Cookie only sets when NOT using JSON.stringify

I am creating cookies using jQuery cookie, which are setting when I don't use JSON.stringify as in the following:

$.cookie("previousObject", savedObjs);

but which do not set when I use JSON.stringify(), as in the following:

$.cookie("previousStories", JSON.stringify(savedObjs));

I have also tried the following:

$.cookie.json = true;
$.cookie("previousObject", savedObjs);

The cookie that should be being created logs to the console,but when I look under resources in the browser, there are no cookies there.

How do I make these cookies work?

Upvotes: 0

Views: 531

Answers (1)

unconditional
unconditional

Reputation: 7656

You don't need to explicitly stringify an object before passing it to $.cookie() since the latter does this for you automatically anyway.

Here's the part of its code that encodes your value:

function stringifyCookieValue(value) {
    return encode(config.json ? JSON.stringify(value) : String(value));
}

So your last bit of code is actually right:

$.cookie.json = true;
$.cookie("previousObject", savedObjs);

In Firefox you can find your cookies in Storage Inspector: https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector#Cookies

Chrome shows them in Resources: https://developer.chrome.com/devtools/docs/resource-panel#cookies

Upvotes: 1

Related Questions