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?

+1


a source to share


3 answers


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

+1


a source


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

+1


a source


Have you tried adding an expiration date to the cookie so it won't set it?

document.cookie = "stylesheet=blue; expires=Thu, 5 May 2011 20:47:11 UTC; path=/"

      

This is a hard-coded example, but you can set the datetime as needed.

0


a source







All Articles