Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create array in cookie with javascript

Is it possible to create a cookie using arrays?

I would like to store a[0]='peter', a['1']='esther', a['2']='john' in a cookie in JavaScript.

like image 239
limfreak Avatar asked Dec 17 '10 12:12

limfreak


People also ask

Can a cookie hold an array?

Cookies can hold only strings. If you want to simulate an array you need to serialize it and deserialize it.

How would you store an array in a cookie?

Example - store array in a cookie: var arr = ['foo', 'bar', 'baz']; var json_str = JSON. stringify(arr); createCookie('mycookie', json_str);

Can you create cookies with JavaScript?

JavaScript can create, read, and delete cookies with the document. cookie property.

Can cookies store object?

Store objects in the CookiesThe cookies store information in the string format only. If users want to store any other types of data in the cookies, they need to convert it to the string using the stringify() method. In this section, we will convert the object to a string and store it in cookies.


2 Answers

As you can read in this topic:

You combine the use jQuery.cookie plugin and JSON and solve your problem.

When you want to store an array, you create an array in JS and use JSON.stringify to transform it into an string and stored with $.cookie('name', 'array_string')

var myAry = [1, 2, 3]; $.cookie('name', JSON.stringify(myAry)); 

When you want to retrive the array inside the cookie, you use $.cookie('name') to retrive the cookie value and use JSON.parse to retrive the array from the string.

var storedAry = JSON.parse($.cookie('name')); //storedAry -> [1, 2, 3] 
like image 191
Anton Tsapov Avatar answered Oct 06 '22 14:10

Anton Tsapov


Cookies can hold only strings. If you want to simulate an array you need to serialize it and deserialize it.

You could do this with a JSON library.

like image 24
Quentin Avatar answered Oct 06 '22 14:10

Quentin