How do I 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 a cookie needs to be checked and whether it is 20 minutes or not. So I wrote a code similar to this code. This is just the javascript code I have pasted.

function checkcookie()
{
    var difftime= getcookie();
    // further operation comes here
}

var cookieminutes;

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

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

        var date =  new Date();
        var minutes = date.getMinutes();

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

    }
}

      

In the getcookie function, the cookieminutes variable comes in as undefined. But as I know, since this is a global variable, it must have a value.

Can anyone please tell me what this solution is for?

+1


a source to share


2 answers


You are setting a value for cookieminutes at the top of the if statement, so any links in the else section will be empty.

Try the following:



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

    cookiedate = new Date();
    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 =  new Date();
        var minutes = date.getMinutes();

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

    }
}

      

+1


a source


If you want to use globals (generally bad design), set and access them explicitly with a window. For instance:.

window.cookieminutes = cookiedate.getMinutes();

      

and later:



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

      

And discard var cookieminutes;

As I said in my comment, it looks like if getcookie is 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 are not using undefined variables.

-4


a source







All Articles