2

Possible Duplicate:
Allowed characters in cookies

I'm using JSON.stringify to convert an object to save it in a cookie. But after saving Arabic Windows-1256 encoding in a cookie, I wasn't able to restore it. Here's what I did:

For example:

Convert and save in a cookie.

conv[user]   = {"user":1,"u":1,"m":3,"c":255,"comment":'السلام عليكم ورحمه الله'};
addCookie('chat_conversations', JSON.stringify(conv) , 7);

Restore value from cookie:

var con  = is_cookie('chat_conversations');
conv = jQuery.parseJSON(con);

Getting my JSON result:

alert(conv[1].comment);

Result

"'D3D'E 9DJCE H1-EG 'DDG H(1C'*G\n"

Here's the result of my cookie

chat_conversations={"1":{"user":"1","u":"1","m":3,"c":255,"comment":"'D3D'E 9DJCE H1-EG 'DDG H(1C'*G\n"}}; expires=Sat, 08 Dec 2012 15:00:42 GMT; path=/; domain=127.0.0.1

How can I save an object containing Arabic in a cookie and restore it?

Community
  • 1
  • 1
Mona Abdelmajeed
  • 686
  • 1
  • 9
  • 19
  • 2
    Well, I'll be honest. I just used your code in my Localhost and I cannot replicate this issue; Although< I didn't use windows-1256, I used UTF-8. – Ohgodwhy Dec 01 '12 at 15:17
  • Check when exactly did you encode your string to windows-1256. JSON uses UTF-8 by default, so maybe you'll have to do extra work to encode/decode. – JofryHS Dec 01 '12 at 15:19
  • + take a look at this thread: http://stackoverflow.com/questions/1969232/allowed-characters-in-cookies – hereandnow78 Dec 01 '12 at 15:20
  • 1
    Use `escape` on the string which isn't working as expected and `unescape` when retrieving it. – Paul S. Dec 01 '12 at 15:21
  • @Ohgodwhy , My encoding is 'utf-8' but the Arabic characters are 'windows-1256' encode , it work fine for english but not with arabic – Mona Abdelmajeed Dec 01 '12 at 15:42

1 Answers1

2

You should sanatise strings going into a cookie using escape or encodeURIComponent (minor differences between the two, see below) and then reverse this via unescape or decodeURICompontent when retrieving the data.

// Create obj using safe chars only
conv[user] = {
    "user" : 1, // (numbers are fine as they are)
    "u" : 1,
    "m" : 3,
    "c" : 255,
    "comment" : escape('السلام عليكم ورحمه الله') // by escaping potentially unsafe chars
};
// save
addCookie('chat_conversations', JSON.stringify(conv) , 7);
// retrieve
var con  = is_cookie('chat_conversations');
conv = jQuery.parseJSON(con);

var comment = unescape(conv[1].comment); // unescape what was escaped earlier
alert(comment);
// "السلام عليكم ورحمه الله"

escape is fine because you just want to use this data in JavaScript. If you want to access the cookie server-side then I'd strongly recommend using encodeURIComponent.

If you are just using it for JavaScript, consider window.localStorage because it will cause less internet usage.

Paul S.
  • 64,864
  • 9
  • 122
  • 138