Can't able to set expiry date in cookie using javascript? - 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 ...

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)

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

Related

JavaScript cookie that expires after one day

I'm attempting to learn to set a JS cookie that expires after one day, but our client is reporting intermittent results with this. Am I missing something? Is there a better way to go about doing this?
Honestly, I'd also be open to setting a session cookie to alleviate the problem, but I figured I'd see if someone spotted an error in the way we're doing this here first.
Thank you!
(function($){
checkCookie();
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var noShowWelcome = getCookie("sameSessionSKF");
if (!noShowWelcome) {
$('#home-alert').modal({
fadeDuration: 500
});
setCookie('sameSessionSKF', true, 1); // sets to expire after 1 day
}
}
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Instead of expires you can specify Max-Age, which is the number of seconds until the cookie expires.
const maxAge = 86400
document.cookie = cname + "=" + cvalue + ";Max-Age=" + maxAge + ";path=/";

Create and Delete cookies for external websites on their subdomain

Set Cookie function in Jquery
function setCookie(cookieName, cookieValue, cookieExpireDays) {
var d = new Date();
d.setTime(d.getTime() + (cookieExpireDays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";" + "path=/";
}
Delete function in Jquery
function deleteCookie(name) {
var domain = location.hostname,
path = '/'; // root path
document.cookie = [
name, '=',
'; expires=' + new Date(0).toUTCString(),
'; path=' + path,
'; domain=' + domain
].join('');
}
This works fine for local links, but when I try to use it on external websites. I can get my document.cookie but deleteCookie function does not delete the cookie. Any ideas?
*Please remember, I am just running these scripts from console of Google Chrome
I might be misunderstanding something in your question, but here's how I handled the getting, setting, and deleting of a cookie I set.
fiddle: https://jsfiddle.net/hmvyu3L6/
<button class='set'>set</button>
<button class='get'>get</button>
<button class='delete'>delete</button>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = 'expires=' + d.toUTCString();
document.cookie = cname + '=' + cvalue + '; ' + expires;
}
function getCookie(cname) {
var name = cname + '=',
ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return '';
}
function deleteCookie( name ) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
var value = 'hey there';
$('.set').on('click', function() {
setCookie('testCookie', value, 360);
});
$('.get').on('click', function() {
console.log(getCookie('testCookie'));
});
$('.delete').on('click', function() {
deleteCookie('testCookie');
});
If the cookies are HttpOnly, you will not be able to delete them using javascript or jquery.
Make sure your domain and path match exactly. If they are different (e.g. .subdomain.domain.com instead of .domain.com, or /path instead of /) then the script will not affect the cookies.
Alright, I am answering my own question because I changed few things and it works now.
var domain = location.hostname
function setCookie(cookiename, cookievalue, expiredays, domain) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expiredays=" + date.toGMTString();
document.cookie = cookiename+ "=" + cookievalue+ expires + "; domain=" + domain + "; path=/";
}
function deleteCookie(cookiename, domain) {
setCookie(cookiename, "", -1, domain);
}
deleteCookie("Cookie_Name",domain)

Remove Cookies In Jquery on logout button

Hi i am trying to make code for clear cookies in jquery onclick of logout button but didn't get solution
function logout()
{
document.cookie = 'Visit=; expires='+new Date(0).toUTCString() +'; path=/FinalVertozz/';
window.location='../login.html';
}
cookies details
Name: Visit
Content: 09850227123455130
Domain: localhost
Path: /FinalVertozz
Send for: Any kind of connection
Accessible to script: Yes
Created: Saturday, October 4, 2014 11:25:45 AM
Expires: When the browsing session ends
Can you use simple javascript. It's easy.
function ClearCookies()
{
var cookiesCollection = document.cookie.split(";");
for (var i = 0; i < cookiesCollection .length; i++)
{
var cookieName = cookiesCollection [i];
var pos= cookieName.indexOf("=");
var name = pos> -1 ? cookieName.substr(0, pos) : cookieName;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
From the reference of this question and answer from #Russ Cam
How do I set/unset cookie with jQuery?
Use this function to reuse
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = escape(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 unescape(c.substring(nameEQ.length, c.length));
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
Hope it may help :)
This issue is the path. If you remove it things will work.
document.cookie = 'Visit=; expires='+new Date(0).toUTCString();
Also, you're not using any jQuery in the above example. The question may be better stated as "remove cookies in JavaScript on logout button".

how to store on click appended html in to client side cookies

I am trying to append some data on run time..
now I have to store this appended data into client side Cookies.
Any suggestion much appreciated. Thanks in advance.
here is the code and fiddle URL:
$('#add').on('click', function(){
var inputHTML = $('#inputName').val();
$('<li>'+inputHTML+'</li>').appendTo('#inputBox > ul');
});
http://jsfiddle.net/ft26u/12/
You can use localStorage, like this:
$('#add').on('click', function(){
var inputHTML = $('#inputName').val();
$('<li>'+inputHTML+'</li>').appendTo('#inputBox > ul');
var myData = localStorage.cookieData ? JSON.parse(localStorage.cookieData) : new Array();
myData.push(inputHTML);
localStorage.cookieData = JSON.stringify(myData);
console.log(myData);
})
Use these functions:
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = escape(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 unescape(c.substring(nameEQ.length, c.length));
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
Edit Updated sample to load cookie on load
http://jsfiddle.net/aZXMr/3/

Getting value from a cookie

I have set a cookie using the following and it works well. I can see it in browser cookie(console).
But how can i get back the value from cookie ??
days = 1;
cookiename = 'uid';
cookieValue = result.pp.uid;
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 = cookiename + "=" + cookieValue + expires + "; path=/";
I have the following code , but i dont want to use the function.
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;
}
Ive no idea of how they are getting the value of cookie..
Is there a simple way like document.cookie ?
Try this library
https://github.com/carhartl/jquery-cookie
Also see this SO post
How do I set/unset cookie with jQuery?
Example from their docs
Read cookie:
$.cookie('the_cookie'); // => "the_value"
$.cookie('not_existing'); // => undefined

Categories