0

I am saving an object in a JQuery $.cookie using the following code:

  var contactData = { Name: 'Michael', 
                      Age: 29
                    };

  $.cookie("contact", $.param(contactData), { expires: 20 });

and I was wondering how I can access the Age and Name saved in $.cookie? Thanks

NOTE: This question is not a duplicate of the question mentioned above. I sincerely believe that those who marked it as duplicate for this question didn't take a moment to read the question and understand it in full. My Question is not about saving / reading from $.cookie, it is rather about reading specific property of json saved in the cookie. For example reading the Name only or Age only but not both

MChan
  • 6,842
  • 27
  • 83
  • 132
  • Did you guys try to read my question carefully? I am not trying to read a value as is, as I know how to do this, I am trying to access a property in an object and made a trial using $.cookie['contact']['token'] and it didn't work – MChan Mar 15 '14 at 01:25
  • As Paul set, you will only get a URL-encoded string value back – so you could go either with the plugin he suggested; or encode your data as JSON before storing it into the cookie, and decode it after reading. – CBroe Mar 15 '14 at 02:13
  • @MChan: well then in that case [this question](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) would be appropriate, though it seemed that you didn't know how to actually access the cookie's value. – Qantas 94 Heavy Mar 15 '14 at 09:26

1 Answers1

2

To access your cookie value, use

$.cookie('contact')

However, this will result in:

"Name=Michael&Age=29"

You can use this jquery plugin to deparse your value:

https://github.com/AceMetrix/jquery-deparam

This would allow you to use:

$.deparam($.cookie('contact'))['Age']
Paul Way
  • 1,966
  • 1
  • 13
  • 10