I am pulling my hair out with this error, although I am sure that this is something obvious. Sorry if so.
The following javascript successfully sets my cookie:
<script type="text/javascript"> $(document).ready(function(){ $.post('../setCookie.php',{'region':'test'}); }); </script>
But as soon as I bind the same code to the onclick event, for example ...
<script type="text/javascript"> $(document).ready(function(){ $("#us a").click(function(){ $.post('../setCookie.php',{'region':'en-us'}); }); $("#uk a").click(function(){ $.post('../setCookie.php',{'region':'en-gb'}); }); }); </script> <ul> <li id="uk"><a href="http://www.example.com/uk"> <span>Enter UK site</span></a></li> <li id="us"><a href="http://www.example.com/us"> <span>Enter US site</span></a></li> </ul>
.. he no longer sets a cookie! Despite the fact that the same code is called executed in exactly the same way (I go through it in order and see everything as it should be).
Repeat: javascript shoots great. I go through setCookie.php and everything is the same ... except for the cookies at the end of it.
What's happening? I assume this is browser security or something like that?
For anyone interested, here is how I solved it:
<script type="text/javascript"> $(document).ready(function(){ $("#us a").click(function(e){ e.preventDefault(); $.post('../setCookie.php',{'region':'en-us'}, function() { window.location = "http://www.example.com/us"; } ); }); $("#uk a").click(function(e){ e.preventDefault(); $.post('../setCookie.php',{'region':'en-gb'}, function() { window.location = "http://www.example.com/uk"; } ); }); }); </script>
source share