Cookie sets on Localhost but not on the real server?
This is my first experience with cookies in JavaScript and below script works fine on my local PC, but when I load it here: example it doesn't work.
$(document).ready(function(){
// Get Cookie
var getCookie = document.cookie;
if(getCookie == "stylesheet=blue")
{
$("[rel=stylesheet]").attr({href : "blue.css"});
}
else if(getCookie == "stylesheet=main")
{
$("[rel=stylesheet]").attr({href : "main.css"});
}
// Set Stylsheet back to Main
$('#reset').click(function()
{
$("[rel=stylesheet]").attr({href : "main.css"});
var setCookie = document.cookie = "stylesheet=main";
});
// Set Stylsheet Blue
$('#blue').click(function()
{
$("[rel=stylesheet]").attr({href : "blue.css"});
var setCookie = document.cookie = "stylesheet=blue";
});
});
Any ideas?
a source to share
The problem is that you are using google analytics which sets its own cookies as well. This way when reading the document.cookie property it will never have a value, e.g. "stylesheet = blue" because it will contain information about other cookies. Call
alert(document.cookie);
and check the meaning for yourself.
You have to use a function to get the cookie value like
function getCookie(N){
if(N=(new RegExp(';\\s*'+N+'=([^;]*)')).exec(';'+document.cookie+';'))
return N[1]
}
or use jQuery cookie
a source to share
When you return the cookie, it is not only the string "stylesheet = blue", but other information as well.
For me, the string I am returning looks like this:
"stylesheet=blue; __utma=168444603.22445052401845424.1242318397.1242318397.1242318397.1; __utmb=168444603.5.10.1242318397; __utmc=168444603; __utmz=168444603.1242318397.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/864324/cookie-sets-on-localhost-but-not-on-live-server"
check that the string contains "stylesheet = blue" instead of checking for equivalence.
Edit . See what @Rafael said. I like the jQuery cookie plugin
a source to share