javascript- site cookies are not deleted - javascript

I am saving and restoring cookies using JavaScript in my website and I encountered an issue where I cannot delete those cookies.
I tries deleting then in code and also by clearing chrome history (from the beginning of time). I have red written posts and tried all sort of things but nothing fixed it for me.
here's my code that handles the cookies:
var createCookie = function (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 = name + "=" + value + expires + "; path=/";
}
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
function deleteCookie(name) {
createCookie(name, "", -1);
}
after deleting chorme history, I execute this line of code :
var cookieHdrStr = getCookie("cart_header");
and I expectcookieHdrStr to be null/undefined but instead it restores the last cookie I saved.

I found what was wrong...
It turns out I had a line of code I wasn't aware of:
window.onbeforeunload = function () { saveDocumentCookie(); }
whenever unloading the page it was saving the cookies, so even when I deleted them and pressed f5 to refresh the page, before refreshing it was saving cookies.

Related

Javascript - Set a Browser Cookie

When a user click on a button it would take them to a link but before they go to that link, the cookie will need to be set to either English (EN) or French (FR). I got an example here:
http://www.quirksmode.org/js/cookies.html
but for some reason, it's not reading in the cookie and I'm not sure where I'm going wrong.
This is what I have:
<!DOCTYPE html>
<html>
<body>
<p>This is for the Browser Cookies.</p>
<button onclick="EN_Cookie()">English Link</button> <button onclick="FR_Cookie()">French Link</button>
<script>
function EN_Cookie() {
setCookie("SMDCookie","EN",7);
//location.href = 'https://google.com';
}
function FR_Cookie() {
setCookie("SMDCookie","FR",7);
//location.href = 'https://google.com';
}
function setCookie(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=/";
}
</script>
</body>
</html>
Any suggestions??
I reviewed your code and found your set cookie function is correct.
May be your getCookie not working, i am sharing get cookie function:
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 "";
}
Here are functions you can use for creating and retrieving cookies
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 = name + "=" + value + expires + "; path=/";
}
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
Copied from How do I create and read a value from cookie with javascript?

Expiration date on javascript cookie is not working -updated

UPDATE - made with suggestions from below:
I have the following script that pops up a window, after 3 visits, and to only 20% of visitors. The expiration date is set and shows in Developer tools for expiring in 180 days, but it's still popping up. What am I doing wrong? Any help is appreciated, I do not know javascript at all very well. This has to be done all in plain javascript - no jQuery
//setting the expiration date to 6 months from now//
expDate = new Date;
// in the following line, 180 means 180 days.//
expDate.setTime(expDate.getTime() + 180 * 24 * 60 * 60 * 1000);
expDate.toGMTString();
//making the cookie//
function setCookie(name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=/wmb" + path : "") +
((domain) ? "; domain=www.example.com" + domain : "") +
((secure) ? "; secure" : "");
}
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else {
begin += 1;
}
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
return unescape(dc.substring(begin + prefix.length, end));
}
//cookie name is called CustomSurvey//
visits = getCookie('CustomSurvey');
if (!visits) {
visits = 1
};
if (visits < 4)
//Math.random is set so that 20% of those visits actually get the popup//
if ((Math.random() * (100 - 1) + 1) < 20) {
//get location of where this popup came from; also contains variable from SM that will trickle down into reporting to tell where it came from//
var currentLocation = window.location;
window.open("https:mysurvey.com" + "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
}
if (visits < 3) {
++visits;
cookieData = visits;
setCookie('CustomSurvey', cookieData, expDate)
}
I changed to what you suggested (except the url - that part is just made up (the real one pops up). I did everything suggested except when I changed the visits > 3 , now nothing pops up (after clearing cache and clicking about 50 times.
This is what I have now:
//setting the expiration date to 6 months from now//
expDate = new Date;
// in the following line, 180 means 180 days.//
expDate.setDate(expDate.getDate() + 180)
//making the cookie//
function setCookie(name, value, expires, path, domain, secure){
document.cookie= name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=/wmb" + path : "") +
((domain) ? "; domain=ptoweb.uspto.gov" + domain : "") +
((secure) ? "; secure" : "");
}
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else {
begin += 1;
}
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
return unescape(dc.substring(begin + prefix.length, end));
}
//cookie name is called CustomSurvey//
visits = getCookie('CustomSurvey');
if (!visits) {
visits = 1
};
if (visits > 3)
//Math.random is set so that 20% of those visits actually get the popup//
if ((Math.random() * (100 - 1) + 1) < 20) {
//get location of where this popup came from; also contains variable from SM that will trickle down into reporting to tell where it came from//
var currentLocation = window.location;
window.open("https://www.surveymonkey" + "?" + currentLocation, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
}
if (visits < 3) {
++visits;
cookieData = visits;
setCookie('CustomSurvey', cookieData, expDate)
}

Javascript onkeyup event

I am using javascript's onkeyup event to display date after a user types in content in a form field.
The date displays properly but on page refresh, the date disappears.
How can I retain that date on my view after page refresh and after browser is closed?
Here is my view form:
<div class="form-group">
{{ Form::label('advance', 'Advance') }}
{{ Form::text('advance', $worker->advance , array('class' => 'form-control', 'placeholder' => 'None', 'id' => 'advance', 'onkeyup=displayDate()')) }}
<strong><p style="margin-top: 10px">Advance issued on : </p>
</strong><p style="margin-top: 20px" id="date"></p>
</div>
Here is my javascript function that displays the date:
<script>
function displayDate() {
var x = document.getElementById("advance");
document.getElementById("date").innerHTML = Date();
}
</script>
Use cookies
You can save your data in a cookie, read it on page load and fill up your form fields accordingly.
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 = name + "=" + value + expires + "; path=/";
}
function readCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}

Show hide javascript cookie

function showhide() {
if( document.getElementById("hidethis").style.display=='none' ){
document.getElementById("hidethis").style.display = 'table-row'; // set to table-row instead of an empty string
}else{
document.getElementById("hidethis").style.display = 'none';
}
}
I have this working javascript function to hide a row in a table - like this
<tr id="hidethis" style="display:table-row;">
It works fine but i want to use cookies to remember which option user chose. I cant figure out how to properly set cookies, some advice would be much appreciated.
Try this:
You need to store the value in cookies and read those values on DOMContentLoaded event ad set your style accordingly
Reference used to create and read cookies values
var createCookie = function(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 = name + "=" + value + expires + "; path=/";
};
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
document.addEventListener('DOMContentLoaded', function() {
var cookieVal = getCookie('display');
if (cookieVal) {
document.getElementById("hidethis").style.display = cookieVal;
}
});
function showhide() {
if (document.getElementById("hidethis").style.display == 'none') {
document.getElementById("hidethis").style.display = 'table-row'; // set to table-row instead of an empty string
createCookie('display', 'table-row', 365);
} else {
document.getElementById("hidethis").style.display = 'none';
createCookie('display', 'none', 365);
}
}
<table>
<tr id="hidethis" style="display:table-row;">
</table>

How to delete the cookie at time of reloading the page?

I have one requirement, at the time of pageloading I'm setting cookie using sessionStorage, once refresh/reload the page I have to delete the cookie.
I tried with the following code, but cookie is not deleting for reload the page,
Can someone help me please,
$(document).ready(function() {
$('#example').dataTable({
"bStateSave": true,
"fnStateSave": function (oSettings, oData) {
sessionStorage.setItem('POSummary', JSON.stringify(oData));
},
"fnStateLoad": function (oSettings) {
return JSON.parse(sessionStorage.getItem('POSummary'));
}
});
} );
Thanks
if you want delete a sessionStorage element you need to do this:
sessionStorage.removeItem("session-name");
if(sessionStorage.getItem('POSummary') != null)
sessionStorage.removeItem("POSummary");
if you want use cookie instead you must implement this two function:
function create (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 erase (name){
create(name, "", -1);
}

Categories

Resources