Storing array into a cookie

Hi, I have a form that when the user is entering their details a few values are stored into an array. However when the form fails validation a error message is returned and the array value is lost. I want to save the array value after the form fails validation, and to achieve this I’m storing the value into a cookie.

var selectedDays = ["2015-11-25", "2015-11-26", "2015-11-27"];
var newStr = selectedDays;
var BookableArr = JSON.stringify(newStr);
Cookies.remove('bookableDates');
Cookies.set('bookableDates', BookableArr);

If the cookie is set then the value of the cookie is returned back into the forms array:

var selectedDays = [Cookies.get('bookableDates')];

But what is actually returned from the cookie is this

 ["2015-11-25","2015-11-26","2015-11-27"]

and on form validation error, selectedDays returns this:

["["2015-11-25","2015-11-26","2015-11-27"]"]

Making it one long array, opposed to multiple array values. Can anyone help me solve this problem?

JSON.parse() ? you did stringify the array manually before putting it into the cookie, so logic dictates that you have to apply the reverse process to get the array again.

1 Like

Ok, like this?

 var rtn = JSON.parse(Cookies.get('bookableDates'));
 var selectedDays = [rtn];

This doesn’t work, it returns -

[["2015-11-25", "2015-11-26", "2015-11-27", "2015-11-28"]]

Almost there:

var selectedDays = JSON.parse(Cookies.get('bookableDates'));
1 Like

If you don’t have to support ancient browsers, you could go for WebStorage. that does data serialisation out of the box.

1 Like

Awesome. Thanks guys, it’s working! :grinning:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.