10

I am using this jquery.cookie plugin and I need to set value to TRUE or NULL/FALSE.

I am trying to do it like this: $.cookie('ff', true, { expires: 30, path: '/' }); but it sets the value to string and not boolean.

Any ways of fixing this?

Alex
  • 7,538
  • 23
  • 84
  • 152
  • 5
    Yes, parse the "true" string to boolean when you read it. – gdoron Mar 17 '12 at 18:06
  • 1
    As far as I know anything stored in cookies is a string, because cookies themselves are strings. So any sort of fix would be on the cookie reading side of it. – d_inevitable Mar 17 '12 at 18:07
  • the thing is that I am reading it with `$this->input->cookie();`'s codeigniter function, does php has any function to do so? – Alex Mar 17 '12 at 18:09

4 Answers4

17

Cookies are only string-valued. As gdoron commented, if you want to treat the value as a boolean, you need to parse it back to a boolean when the cookie value is read back out.

Since you commented that you are reading the cookie value with PHP, see Parsing a string into a boolean value in PHP.

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
6

Client side:

$.cookie('ff', "true", { expires: 30, path: '/' });

Server side:

$cookie = $this->input->cookie() == "true";

EDIT: Cookies are strings. Anything stored to cookies will need to be converted to strings. Hence you have to do the string to boolean conversion on the reading side of it. Above I have put an example for PHP (CodeIgniter).

d_inevitable
  • 4,381
  • 2
  • 29
  • 48
1

If you are just looking to use a cookie as a sort of flag, then just check if the cookie exists and if it does not you can assume it is false:

const isSet = Boolean(cookie.get('my-cookie')) || false

This way you don't need to even worry about the actual value of the cookie and just whether or not it exists.

Dana Woodman
  • 4,148
  • 1
  • 38
  • 35
0

Another way to do this is

var mycookie = !($.cookie("cookiename")=='false')

Or:

if(!($.cookie("cookiename")=='false')){ 
    //mycode 
}

If the value is 'false' then ($.cookie("cookiename")=='false') will return true so we invert it by using ! which return false

if the value is not 'false' then it will return false so we invert it by using ! which return false