1

I'm looking to set a variable in a cookie as an array using PHP.

There will be times when I want to update this array when a user clicks on a form button, but I don't want to have to reload the page when they do this.

I can't set a cookie value to an array so I'm serialising it first. using:

serialize(array('key' => 'value'))

How do I use Javascript or jQuery to unserialize this array, edit it, serialize it and then add it back to the array to be used by PHP or Javascript?

I'm very open to other ways of doing this so if there are better solutions then do let me know.

Thanks in advance.

EDIT: Just to confirm, I don't want to have lots of different cookies with different names, I could end up with a tone of different cookies.

This is to be used for an online shopping basket to store items added to the basket by the user.

I'm looking to have one array with all the items that the user has added to the basket. I don't want to have to reload the page every time they add something new, I just want it to pop up in the corner of the page.

hojkoff
  • 185
  • 1
  • 8

1 Answers1

0

Use JSON instead, PHP has a built-in JSON function for this. JSON is easily converted on the JS side of the equation and can be easily generated and saved back to the cookie.

You'll be able to store any number of items in an array and convert it to and from JSON on both the PHP and JS side and keep it all in a single cookie.

DampeS8N
  • 3,621
  • 17
  • 20
  • Thanks for that, looks like JSON is the best way to do this. When I JSON encode with PHP i get a JSON looking object say: {"key": "value"} and then add it to the cookie. When however I try and read this with Javascript it's telling me that it's a string not an object. Any ideas? – hojkoff Oct 30 '14 at 13:12
  • [Take your pick](http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – DampeS8N Oct 30 '14 at 17:51