vimal1083
vimal1083

Reputation: 8681

Can't able to set expiry date in cookie using javascript?

I am using following function

function setCookie(c_name,value,exdays){
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

setCookie("userName","vimalraj.s",1);

It create cookies in a "session " not with a 24 hours expiry time .

how to fix this ?

UPDATE :

The above code works fine in my colleague's computer Firefox(27.0.1) and it doesn't for me same Firefox version

I even tried "max-age" instead of "expires"

function set_cookie ( cookie_name, cookie_value,
    lifespan_in_days, valid_domain )
{
    // http://www.thesitewizard.com/javascripts/cookies.shtml
    var domain_string = valid_domain ?
                       ("; domain=" + valid_domain) : '' ;
    document.cookie = cookie_name +
                       "=" + encodeURIComponent( cookie_value ) +
                       "; max-age=" + 60 * 60 *
                       24 * lifespan_in_days +
                       "; path=/" + domain_string ;
}

Nothing worked ...

Upvotes: 0

Views: 2150

Answers (2)

Strikers
Strikers

Reputation: 4776

I suggest you to create a new cookie with same cookie name.

now you can set the new expire. This will over ride the existing cookie since both are of same name.

Now the new cookie will have the new expires

old cookie

var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;

new cookie

var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;

I hope this will help

Upvotes: 0

Shyju Pulari
Shyju Pulari

Reputation: 159

Taken from quirksmode.org.

    function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

Here is for one day

createCookie('ppkcookie','testcookie',1)

Upvotes: 1

Related Questions