0

I have a page that has 4 checkboxes that are checked by default. If you uncheck a box, it writes a cookie so that return trips to the page will have saved preferences. The problem I'm having is that the cookies seem to be written no matter what. Going to the page for the first time should create no cookies, but unchecking a box should throw the following code. As it stands, the first time I'm going to my site, the cookies are created.

Where have I gone wrong (I wouldn't be surprised if it is in multiple places).

$('#mycheckbox').change(function() {
if (! this.checked) {
<?php setcookie('key', 'Value', time() + 4800); ?>
}
});
ballofpopculture
  • 741
  • 1
  • 9
  • 18

2 Answers2

4

No, this.checked works.

The problem is that the PHP code will always be run, since it's run on the server-side and not interpreted by the browser. All PHP code is executed before the browser even gets the files.

A solution would be to put that PHP in an external file and use jQuery $.ajax to request that file, which would run the code only when desired.

You could also check out the jQuery $.cookie plugin.

Purag
  • 16,941
  • 4
  • 54
  • 75
0

As @MarkB already said you are mixing up javascript and php. In this case you should set your cookie with javascript in stead of php. See this post to find out more.

The code as you have it now will always set the cookie, as you already noticed, because the server ignores the javascript code and just runs the php code to set the cookie.

Community
  • 1
  • 1
Pevara
  • 14,242
  • 1
  • 34
  • 47