Skip to content Skip to sidebar Skip to footer

How To Handle Cookies In Javascript?

Possible Duplicate: What is the “best” way to get and set a single cookie value using JavaScript I am working on a project where it requires to check cookie and tell whether

Solution 1:

You're only setting a value for cookieminutes in the top section of the if statement, so any references in the else section will be null.

Try this:

functiongetcookie()
{
    var start = document.cookie.indexOf("expires");
    var cookiedate;

    cookiedate = newDate();
    cookieminutes = cookiedate.getMinutes();

    if(start==-1)
    {    
        document.write("Start equal to -1");
        document.cookie="expires="+cookiedate+",path=0,domain=0";    
    }
    else
    {
        document.write("Start not equal to -1");

        var date =  newDate();
        var minutes = date.getMinutes();

        document.write("The difference is "+minutes);
        document.write("<br />Cookie minutes is "+cookieminutes);
        return (minutes-cookieminutes);

    }
}

Solution 2:

If you want to use global variables (generally bad design) set and access them explicitly with window. E.g.:

window.cookieminutes = cookiedate.getMinutes();

and later:

document.write("Cookie minutes is "+window.cookieminutes);

And drop the var cookieminutes;

As I said in my comment, it looks like if getcookie is being called for the first time on a given page load, and the cookie exists (start != -1), cookieminutes is never set. You need to make sure you don't use undefined variables.

Post a Comment for "How To Handle Cookies In Javascript?"