13

Does anyone have a piece of JavaScript code that creates a cookie and stores an array in it? If you also have the code to read through through cookie and delete it, that would be great as well. Thanks!

2 Answers 2

11

have a look at: http://plugins.jquery.com/project/cookie https://plugins.jquery.com/cookie/

to store an array

$.cookie('COOKIE_NAME', escape(myarray.join(',')), {expires:1234});

to get it back

cookie=unescape($.cookie('COOKIE_NAME'))
myarray=cookie.split(',')
Sign up to request clarification or add additional context in comments.

5 Comments

If your data can contain special characters, you should use JSON encode/decode. Otherwise, an entry containing "," will give incorrect decode result.
Okay, thanks. I tried the jquery example above and couldn't get it to work properly. I may just be missing something. You can create cookies while not using a web server correct?
Dang. Yes, you need to have a web server for this... Was hoping not to. Thanks.
there is no way to create cookies without a webserver josh, if you want to test locally you need to setup a home package like xampp
what if you array contains value with ',' within ? then your function is no use.
5

jQuery, Cookie plugin:
Converting an array into a string:

> JSON.stringify([1, 2]);
> '[1, 2]'

Then:

$.cookie('cookie', '[1, 2]');

And then parse it:

JSON.parse($.cookie('cookie'));
> [1, 2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.