Alex Reynolds
Alex Reynolds

Reputation: 96937

How to update expiration date of cookie via jQuery?

I'd like to update the expiration date of a cookie via jQuery. I am using the jQuery cookie plugin.

Here is the code I used to set the expiration date to 8 hours into the future:

var date = new Date();
date.setTime(date.getTime() + (8 * 60 * 60 * 1000));
$.cookie('myCookie', $.cookie('myCookie'), { expires: date });

This created a new cookie with the right name, but the wrong attributes:

What is a correct way to only update the expiration date of a cookie via jQuery?

Upvotes: 2

Views: 6654

Answers (2)

Alex Reynolds
Alex Reynolds

Reputation: 96937

This seems to work:

var date = new Date();
date.setTime(date.getTime() + (8 * 60 * 60 * 1000));
var myCookieValue = $.cookie('myCookie');
$.cookie('myCookie', null);
$.cookie('myCookie', myCookieValue, { expires:date, secure:true, path:'/' });

Upvotes: 2

Baptiste Pernet
Baptiste Pernet

Reputation: 3384

Just my two cents: what is your cookie initially ?

I try ot reproduce your issue with a cookie that is initialize like this:

$.cookie("myCookie", "myValue")

and it worked.

but I tried with a cookie that is initialized like this:

$.cookie("myCookie", {myParameter: "myValue"})

I don't think the cookie jQuery plugin is design to store object. You can only save string value. so When you so $.cookie("myCookie"), it return "[object Object]"

Upvotes: 0

Related Questions