1

Is it possible to edit a field inside a cookie using javascript? The cookie looks like this

cookie_session=[{"id":"1526","username":"test","email":"test@test.com"}]

For example, is it possible to edit the value of the field username?

I'm trying to use

document.cookie="Field=myValue"

But when i use it, it sets the whole value of the cookie to myValue instead of a certain field within it.

Also, would it be possible to parse the value of username to use it later for a POST request?

Stephan
  • 41,764
  • 65
  • 238
  • 329
mormaii2
  • 67
  • 1
  • 1
  • 9

1 Answers1

3

A cookie is simply a string. You are storing javascript objects inside of a cookie. In order to modify a single part of the object, you will need to decode the JSON, edit the property, and re-encode the object back to a string to store it in the cookie.

btw - cookies were not meant to store javascript objects. If you don't need the data on the server, then you are better off using local/session storage. There are jQuery plugins which allow those mechanisms to work in a cross-browser friendly fashion.

EDIT: an example can be found here: Pure Javascript - store object in cookie

Community
  • 1
  • 1
Ryan Wheale
  • 26,022
  • 8
  • 76
  • 96
  • What about parsing a certain field within the cookie? – mormaii2 Oct 15 '12 at 23:42
  • 2
    So since a cookie is simply a string, it has no fields. Now in your case, the string happens to be a string representing a javascript object (JSON). You must first `parse` the JSON back into a real javascript object. At that point, you can change the properties on the object. Then you will have to `stringify` the object back into JSON and save it back in the cookie. – Ryan Wheale Oct 16 '12 at 00:59
  • That sounds really hard, i don't know much about javascript unfortunately. I don't know if it's possible but what i want to do is: when a user visits a page, his username is only stored in a cookie, i read that cookie and username, use it as a variable to send a POST request based on their username. Would that be even possible? – mormaii2 Oct 16 '12 at 15:11
  • You don't really need to know JavaScript in order to understand the difference between an object and a string. Also, I hope you don't have anything important taking place with this username, as your system could get hacked by a 3rd grader. You need to use proper authentication lookup... which is way beyond the scope of this post. In the mean time, do research on JSON, strings, and objects. Here's a jsfiddle explaining it all: http://jsfiddle.net/ryanwheale/RNMWs/ – Ryan Wheale Oct 16 '12 at 19:13