Getting value from a cookie - javascript

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

Related

JavaScript: incrementing a cookie value and printing to the console

According to Set cookie and get cookie with JavaScript, the canonical function to set a cookie is:
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
I'm trying to modify this function so that it:
a) instantiates a counter variable the first time the page loads
b) increments the counter variable each time the page is refreshed
c) prints the current value of the counter variable to the console
Here is my attempt:
function setCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
else {
expires = "";
}
if (!value) { // should I be checking to see if the COOKIE _itself_ exists? (rather than the value)
var value = 1;
} else {
value++;
}
document.cookie = name + "=" + value + expires + "; path=/";
console.log('Cookie value is', value)
}
### EDIT: ###
Here is a function to get the cookie:
function getCookie(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;
}
EDIT 2
Here is what I'm trying based on one of the suggestions:
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
console.log('Cookie value is', value)
}
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;
}
//setCookie('foo', 3, 5);
//var x = readCookie('foo');
//if (x) {
// console.log('this is foo bar!')
//}
let t = readCookie('foo') || 0;
setCookie('foo', t++, 5);
This results in:
Cookie value is 0
##########################################
Calling setCookie('test', 1, 5) results in:
Cookie value is 2
I get a value of 2 even when loading the page for the first time (presumably because there is a numerical value passed for value when the function is called).
Should I be checking to see if the cookie itself exists (rather than a numerical value for the value argument)?
I would greatly appreciate any assistance with implementing a, b, and c above.
Thanks!

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=/";

jquery plugin to manage cookies

I have to create, update, delete, get the cookies in my project for different products. So is there any jquery plugin for this. Now i am using this to mange cookies in my project.
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);
}
I need a plugin for this which can also update the previous cookie with new product and their value.
There are several plugins for jQuery cookies. You may try https://github.com/carhartl/jquery-cookie or https://plugins.jquery.com/cookie/ or just Google it. and find many other plugins.

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".

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 ...
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

Categories