I'm pulling my hair out with this bug, although I'm sure it's something obvious. Apologies if it is.
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 tie the same code to an onclick
event, like so...
<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>
..it no longer sets a cookie! Even though the same code is called an executed in exactly the same way (I step through it fine, and see everything as it's supposed to be).
Repeat: The javascript is firing fine. I am stepping through setCookie.php and everything is the same... except no cookie at the end of it.
What's going on? I'm guessing it's browser security or something?
For anyone who's interested, here's 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>