7

I'm using this short snippet of code:

var d = itemID + "," + quantity;
var CookieData = $.cookie("storebasket");

if(CookieData == null || CookieData == "") {
    $.cookie("storebasket", d, { path: '/', expires: 60 });
} else {
    $.cookie("storebasket", CookieData + "|" + d, { path: '/', expires: 60 });
}

However the value ALWAYS becomes HTML encoded. For example:

5%2C1

Which when decoded with this tool is:

5,1

I've tried using unescape but no luck:

$.cookie("storebasket", unescape(d), { path: '/', expires: 60 });

Any more ideas?

Tom Gullen
  • 61,249
  • 84
  • 283
  • 456

2 Answers2

13

jquery.cookie is encoding the comma by default. To override this just do:

$.cookie.raw = true;
brad oyler
  • 3,669
  • 1
  • 20
  • 22
0

This answer is really useful:

Allowed characters in cookies

But I really don't see the problem. When you want to use them in your document, you can unescape them. If you want to store them in the cookies, they are being escaped.

Community
  • 1
  • 1
Jonny Burger
  • 922
  • 4
  • 11
  • The problem is is that if Javascript is disabled the site falls back to it's non JS version. The server side cookie setting doesn't HTML encode the data, so when JS decides to encode it we don't know server side whether it needs decoding or not. – Tom Gullen Apr 17 '12 at 17:44
  • What if you always decode it on the server side? As far as I know, a decoded string stays the same when you decode it. – Jonny Burger Apr 17 '12 at 17:51
  • 1
    It might not be safe to do that in every case, for example if we want to store `%20` as a value – Tom Gullen Apr 17 '12 at 17:54
  • Ok. What about using another character than comma, that gets not encoded? Only comma, white-space and semicolon are disallowed. – Jonny Burger Apr 17 '12 at 17:58
  • It's a possible idea, but it's more of a hack that could raise problems in the future. The best way to solve this problem is by making it store the value in the cookie in a non HTML encoded way. It will also be more confusing and time consuming to modify for anyone else who has to maintain it in the future as well – Tom Gullen Apr 17 '12 at 18:01
  • What about base64 encoding the cookie and then decode it afterwards on the server? Even YouTube does use base64 encoding in cookies. All base64 characters don't get urlencoded. – Jonny Burger Apr 17 '12 at 18:07
  • I agree that Tom Gullen has a real issue. I'm trying to create a cookie for a third-party script to read. Since I can't control their script, just choosing how to decode the cookie is not an option. – JellicleCat May 02 '12 at 15:29