Hi All,

I am having trouble getting this javascript to set a cookie on any browser. Below are the two scripts I am using and if anyone can save me from this week of frustration by telling me what I am doing wrong, I would greatly appreciate it.

This is the readCookie script that properly redirects after not finding the cookie.

<script> 
<!-- 

// page to go to if cookie does not exist 
go_to = "http://www.mywebsite.com/index.html"; 

function readCookie(TheCookieName){ 
var start = document.cookie.indexOf(TheCookieName); 

if (start == -1){ 
window.location = go_to; 
} 
else{ 
document.cookie = "access=no; expires=" + ged(num_days); 
} 
} 

readCookie("access"); 
// --> 
</script> 

This is the setCookie script that is not working for me.

<script type="text/javascript">
<!--
// function setCookie('TheCookieName', 'MyValue', '3', '/', '.mywebsite.com', ")
{ document.cookie = name + "=" + escape(value) + "; ";

if(expires){expires = setExpiration(expires);
document.cookie += "expires=" + expires + "; ";
}
if(path){
document.cookie += "path=" + path + "; ";
}
if(domain){
document.cookie += "domain=" + domain + "; ";
}
if(secure){
document.cookie += "secure; ";
}
}

function setExpiration(cookieLife){
var today = new Date();
var expr = new Date(today.getTime() + cookieLife * 24 * 60 * 60 * 1000);
return expr.toGMTString();
}
// -->
</script>

Does anyone know why this cookie is not being set on my browsers? And 'yes' I have javascript enabled and I accept cookies. Any assistance will be greatly appreciated.

Thank you so much.

Can you please make it clear if this one's intentional?
// function setCookie('TheCookieName', 'MyValue', '3', '/', '.mywebsite.com', ")
It's located at line 3 of your second example. Currently, it's commented and wouldn't run the function.

Hello gon1387...

Yes, that 3rd line is intentional. I replaced the actual "cookieName" with 'TheCookieName' and instead of my actual website, I replaced that with '.mywebsite.com' simply for the example on this site (Daniweb).

Are you not able to run this function either?

You won't be able to run the script with that comment on because of the curly bracket pair... Anyway, your doesn't give all of the script... Where are those variables from (i.e. expire, path, secure, domain, etc.)? Did you declare them somewhere? How is the script supposed to be called from and when? What browser are you using to test it?

Hi Taywin,

Thanks for your response...

Are you saying that because I have curly brackets in this script, it will not function?

And I have setup a website already and those variables (i.e. expire, path, secure, domain, etc.) are not the real variables in my actual script and they should be declared from my hosted server once I upload it to that specified server, right?... But everything else is exactly the same.

In my previous script, I included an 'onLoad' function at the end of this code that didn't set the cookie any better than the script above... I hope that answered the questions you were asking?

Setting this javascript cookie has been frustrating the me to no ends, and because the majority of site is constructed in html, I am not prepared to rework everything to php simply to get this setCookie function working.

Thank you again though for any assistance you can provide.

Sorry, my misunderstanding with the curly bracket.

OK, so you do not save any value from cookies to your PHP variables but the other way around (from PHP to cookies), correct?

The current script won't do any thing with cookie if the value of, for example, expire variable doesn't exist -- undefined, false, or 0. That's why it does nothing.

Also, you don't use += but instead use = when you do document.cookie =.

Hey Taywin,

Thanks for the advice, I am going to get rid of the "+" and then give that a shot.

In the original setCookie script, I do give a value to each variable, such as giving expire a '3' value, or path a "/" value and I give domain a "realDomainName" in the real script... I just put fake values in the example above... But if this works I think I will definitely have to give you some money through paypal because this script has been draining.

Hi Lucardy,
So far, I can't see any problem with your script except for the commented line, which supposedly should look like this:

function setCookie(name, value, expires, path, domain, secure){
    //Creates the cookie data
    document.cookie = name + "=" + escape(value) + "; ";

    //sets the expiration of the cookie if there's one
    if(expires){
        expires = setExpiration(expires);
        document.cookie += "expires=" + expires + "; ";
    }

    //sets the path of the cookie if there's one
    if(path){
        document.cookie += "path=" + path + "; ";
    }

    //sets the domain of the cookie if there's one
    if(domain){
        document.cookie += "domain=" + domain + "; ";
    }

    //sets the secure option of the cookie if there's one
    if(secure){
        document.cookie += "secure; ";
    }
}

If you used it like that, then there won't be any problem.
You can use it like this:

//Set a data
setCookie("MyData","MyValue");
//Sets the cookie to expire in two days
setCookie("MyData","MyValue",2);

On the other hand, if you're going to run your code, the one below:

{ document.cookie = name + "=" + escape(value) + "; ";
if(expires){expires = setExpiration(expires);
document.cookie += "expires=" + expires + "; ";
}
if(path){
document.cookie += "path=" + path + "; ";
}
if(domain){
document.cookie += "domain=" + domain + "; ";
}
if(secure){
document.cookie += "secure; ";
}
}

Then, you have to specify to us, where you set the name and value, or (optionally) expires, path, domain, and secure variable. Also can you tell us what data you assigned on those variables, and how they were assigned? It seems the problem was made on those context.

But if this works I think I will definitely have to give you some money through paypal because this script has been draining.

No thank you. I do not do this for money on the forum. It is just for my practice and learning at the same time. Often time, I see some cases that I have not seen before and would get me think about it. Then I would try to reproduce and get it to work because I, myself, may encounter the same issue in the future.

The change from += to = is from my testing on Firebug (a JavaScript plug-in debugger for firefox). If I use +=, it does not add the cookie name & value to the existing cookie list. If I use =, it will automatically append the cookie name & value to the existing cookie. That's how I recall the way it is being used. Below is the setCookie() function which is a portion of my own cookie class I implemented (using prototype fashion).

/*****
 * Set up acookie with value and expiration date.
 *
 * @param  value  A string of cookie value
 * @param  expiredays  An integer of number of days for cookie to be good
 *                     (-1 means to delete it)
 */
DocCookieKlass.prototype.setCookie = function(value, expiredays) {
  var exdate=new Date()
  exdate.setDate(exdate.getDate()+expiredays)
  document.cookie = this.cName+"="+escape(value)+(!isNaN(expiredays)) ? "" : "; expires="+exdate.toGMTString())
}  // setCookie(int/string, int)

Thank you guys, but nothing seems to be working with this particular script I have, and I'll try your code out, Taywin, in about fours hours.... My eyes and body need to take a break from my computer and this particular script because I am getting a serious headache from this.

What browser are you using in debugging JavaScript? I suggest you to use Firebug with Firefox for debugging because it is much easier and the plug-in will tell you what error it occurs. Even if you are working for cross-browser scripts, you should start with Firebug. Often times, it gets rid of headache for me.

Thanks Taywin, I'll give Firebug a shot.

I have tried several other javascripts this past month and none of them seem to work... I insert this code within the head of my page and still nothing:

<script type="Javascript">
function setCookie('cookieName', 'cookieValue', 'cookieExpires', "cookiePath", '.domainName', "")
{document.cookie = name + "=" + escape(value) + "; ";
if(expires){expires = setExpiration(expires); document.cookie += "expires=" + expires + "; ";}
if(path){document.cookie += "path=" + path + "; ";}
if(domain){document.cookie += "domain=" + domain + "; ";}
if(secure){document.cookie += "secure; ";}}

function setExpiration(cookieLife){
var today = new Date();
var expr = new Date(today.getTime() + cookieLife * 24 * 60 * 60 * 1000);
return  expr.toGMTString();}
</script>

And of course I replace the "cookieName/Path/Value/Expire..etc" in the example above, but yet I still do not get the cookie stored on my browsers (Chrome, IE, Firefox, etc...).

I don't get it... I am completely lost... And absolutely tired.

If anybody has had a similar problem, I would appreciate any assistance that can be provided...

I will donate $100 to anybody's Paypal account that can figure this out because I have almost all but given up :(

Thank you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.