JavaScript function deleteCookie() is not working for me - javascript

I am trying to learn JavaScript and got hung up on trying to create a button that deletes a cookie, but my code simply is not working and I have been stuck on this for hours now.
For convenience, the page is hosted here:
http://kazmer.x10host.com/Week4/delete_cookie_test.html
The cookie.js is located here:
http://kazmer.x10host.com/Week4/cookies.js
The code in the external cookies.js is the following:
function createCookie(name, value, days, path, domain, secure) {
if (days) {
var date = new Date();
date.setTime( date.getTime() + (days*24*60*60*1000));
var expires = date.toGMTString();
}
else var expires = "";
cookieString = name + "=" + escape (value);
if (expires) cookieString += "; expires=" + expires;
if (path) cookieString += "; path=" + escape (path);
if (domain) cookieString += "; domain=" + escape (domain);
if (secure) cookieString += "; secure";
document.cookie = cookieString;
}
function getCookie(name) {
var nameEquals = name + "=";
var crumbs = document.cookie.split(';');
for (var i = 0; i < crumbs.length; i++) {
var crumb = crumbs[i].trim();
if (crumb.indexOf(nameEquals) == 0) {
return unescape(crumb.substring(nameEquals.length,crumb.length));
}
}
return null;
}
The HTML for the page also has some JS in it:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Delete Cookie Test</title>
<meta charset="UTF-8" />
<meta name = "description" content = "JavaScript Test" />
<script src="cookies.js"></script>
<script>
window.onload = function() {
var cookievalue = prompt("Cookie Value:");
createCookie("myCookieData", cookievalue);
}
function viewCookieInfo() {
document.getElementById("output").innerHTML = "Your cookie value: " + getCookie("myCookieData");
}
function deleteCookie(name) {
name="myCookieData";
createCookie(name,"",-1);
}
</script>
</head>
<body>
<button type="button" onclick="viewCookieInfo()" >Display Cookie Info</button><br>
<div id="output"></div><br>
&nbsp &nbsp <button type="button" onclick="deleteCookie()" >Delete Cookie</button>
</body>
</html>
I understand the concept of expiring the cookie, but it's just not working and I hope someone will point out my error(s) here.
Thank you in advance!

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?

Live Cookie Checker in js

I'm working on a solution that checks the cookies in real time.
Once you have opened a link, a cookie is created. This cookie should be checked in real time and depending on the content, the corresponding text (send button) should be displayed.
The code works. Where I have the problem is with the IF sequence, which should be checked again and again without reloading the page.
<script language="JavaScript" type="text/javascript">
function SetCookie(cname, cvalue) {
var d = new Date();
d.setTime(d.getTime() + (3560*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires;
};
function getCookieValue(a) {
var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
return b ? b.pop() : '';
};
</script>
<img src="bilder/icon.png" height="75">
<script language="JavaScript" type="text/javascript">
if (getCookieValue("klickonbutton") == 'ja') {
document.write ('<input type="submit" value="Senden" id="senden">');
} else {
document.write ('<p><b><font color="#FF0000">Error Message</b></font></p>');
document.write ('<input type="submit" value="Senden" id="senden" disabled="disabled">');
};
</script>
document.write deletes the entire HTML and adds the Html which you specify in the parameter. Instead what you should do is add the button and error div on the HTML and toggle the display of these based on the cookie value. Check out the sample code.
<img src="bilder/icon.png" height="75">
<input type="submit" value="Senden" id="senden">
<p style="display: none" id="error"><b><font color="#FF0000">Error Message</b></font></p>
<script language="JavaScript" type="text/javascript">
function SetCookie(cname, cvalue) {
var d = new Date();
d.setTime(d.getTime() + (3560*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires;
checkIsCookieAvailable();
};
function getCookieValue(a) {
var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
return b ? b.pop() : '';
};
function checkIsCookieAvailable() {
const senden = document.querySelector('#senden');
const error = document.querySelector('#error');
setInterval(() => {
if (getCookieValue("klickonbutton") == 'ja') {
senden.style.display = 'block';
senden.disabled = false;
error.style.display = 'none';
} else {
error.style.display = 'block';
senden.disabled = true;
}
}, 1000)
}
</script>

Cookie values consistently returning null

I'm attempting to use a prompt to have someone enter a value, make that value into a cookie, then have a link that will redirect that person to a second page where their cookie value would be displayed. The issue I'm running into is that the cookie in question continues to be returned null, no matter what I input. Any help would be appreciated!
This is meant to be a Javascript code.
First Page (Prompt Page)
<!DOCTYPE html>
<html>
<head>
<title>Event Handlers</title>
<script>
function createCookie(name, value, days, path, domain, secure) {
if (days) {
var date = newDate();
date.setTime( date.getTime() + (days*24*60*60*1000));
var expires = date.toGMTString ();//code
}
else var expires = "";
cookieString = name + "=" + escape(value);
if (expires) cookieString += ";expires=" + expires;
if (path) cookieString += "; path=" + escape (path);
if (domain) cookieString += "; domain=" + escape (domain);
if (secure) cookieString += "; secure";
document.cookie = cookieString
}
function getCookie(name) {
var nameEquals = name + "=";
var crumbs = document.cookie.split(';');
for (var i = 0; i < crumbs.length; i++) {
var crumb = crumbs[i];
if (crumb.indexOf(nameEquals) == 0) {
return unescape(crumb.substring(nameEquals.length, crumb.length));
//code
}
}
return null;
}
function deleteCookie(name) {
createCookie(name,"",-1);
//code
}
</script>
<script>
window.onload = function() {
var cookievalue = prompt("Cookie Value:");
createCookie("myCookieData", cookievalue);
}
</script>
</head>
<body>
Go to Cookie Test Page 2
</body>
</html>
Second Page (Display Cookie Page)
<!DOCTYPE html>
<html>
<title>Cookie Testing</title>
<head>
<script>
function createCookie(name, value, days, path, domain, secure) {
if (days) {
var date = newDate();
date.setTime( date.getTime() + (days*24*60*60*1000));
var expires = date.toGMTString ();//code
}
else var expires = "";
cookieString = name + "=" + escape(value);
if (expires) cookieString += ";expires=" + expires;
if (path) cookieString += "; path=" + escape (path);
if (domain) cookieString += "; domain=" + escape (domain);
if (secure) cookieString += "; secure";
document.cookie = cookieString
}
function getCookie(name) {
var nameEquals = name + "=";
var crumbs = document.cookie.split(';');
for (var i = 0; i < crumbs.length; i++) {
var crumb = crumbs[i];
if (crumb.indexOf(nameEquals) == 0) {
return unescape(crumb.substring(nameEquals.length, crumb.length));
//code
}
}
return null;
}
function deleteCookie(name) {
createCookie(name,"",-1);
//code
}
</script>
<script>
window.onload = function () {
document.getElementById("output").innerHTML = "Your cookie value: " + getCookie("myCookieData");
}
</script>
</head>
<body>
Back to Cookie Test Page 1<br />
<div id="output"></div>
</body>
</html>
In addition, if anyone can give tips on to how to add a button to the second page to delete the cookies from the first page, that would also be greatly appreciated! But for now, I'd just like to figure out why my cookies keep being returned null. Thanks in advance!
Cookies are not allowed in local files on some browsers. So if you're using local files - try uploading those files to a server and trying again. Works for me.
To add a cookie delete button you can use:
<input type="button" onClick="deleteCookie('myCookieData')" />

writing cookie with a domain name

Below is the code I am writing to set the cookie with domain name= “.example.com” but this isn’t working. Any idea what’s wrong with the code? However if I remove the domain name, it works fine.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function setCookie(c_name,value,exdays)
{
alert("Cookie = " + document.cookie);
var c_value=escape(value);`enter code here`
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = c_name +"=" + value + ";expires=" + myDate + ";domain=.example.com;path=/";
}
</script>
</head>
<body onload="setCookie('name','value')">
</body>
</html>
Try these functions. It might help ;)
cookie_create = function (name,value,days) {
var expires, date;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
expires = date = null;
};
cookie_read = function (name) {
var nameEQ = name + "=",
ca = document.cookie.split(';'),
len = ca.length,
i, c;
for(i = 0; i < len; ++i) {
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);
}
nameEQ = name = ca = i = c = len = null;
return null;
};
cookie_erase = function (name){
cookie_create(name,"",-1);
name = null;
};
try this
function setCookie(name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "; path=" + "/") +
((domain) ? "; domain=" + domain : "; domain=.example.com") +
((secure) ? "; secure" : "");
}

JavaScript Cookie Length

I am just learning JS cookies. I am able to save the cookie when a person hits a button, but seems the length of period is not correct. I need it to be 15 days, but it keeps saying the length of time is until the end of the session (http://screencast.com/t/ea7TOoGTnbA).
Here is the code I am using below:
<script type="text/javascript">
function getCookie(w){
cName = "";
pCOOKIES = new Array();
pCOOKIES = document.cookie.split('; ');
for(bb = 0; bb < pCOOKIES.length; bb++){
NmeVal = new Array();
NmeVal = pCOOKIES[bb].split('=');
if(NmeVal[0] == w){
cName = unescape(NmeVal[1]);
}
}
return cName;
}
function printCookies(w){
cStr = "";
pCOOKIES = new Array();
pCOOKIES = document.cookie.split('; ');
for(bb = 0; bb < pCOOKIES.length; bb++){
NmeVal = new Array();
NmeVal = pCOOKIES[bb].split('=');
if(NmeVal[0]){
cStr += NmeVal[0] + '=' + unescape(NmeVal[1]) + '; ';
}
}
return cStr;
}
function setCookie(name, value, expires, path, domain, secure){
document.cookie = name + "=" + escape(value) + "; ";
if(expires){
expires = setExpiration(expires);
document.cookie += "expires=" + expires + "; ";
}
if(path){
document.cookie += "path=" + path + "; ";
}
if(domain){
document.cookie += "domain=" + domain + "; ";
}
if(secure){
document.cookie += "secure; ";
}
}
function setExpiration(cookieLife){
var today = new Date();
var expr = new Date(today.getTime() + cookieLife * 60 * 60 * 10);
return expr.toGMTString();
}
</script>
<script language="JavaScript">
// set a cookie which will expire in 3 days and be accessible site wide
setCookie('drunkdriving_cta_overlay', 'Yes', 3, '/');
</script>
<script language="JavaScript"><!--
document.write(getCookie("drunkdriving_cta_overlay"));
//-->
</script>
<?php if (isset($_COOKIE["drunkdriving_cta_overlay"])) {?>
hello?
<?php } else { ?>
goodby
<?php } ?>
Any help would be greatly appreciated.
It looks like the problem is not in setting the cookie, but in the date calculation. Try replacing your setExpiration method with this:
function setExpiration(cookieLife){
var expires = new Date();
expires.setDate(expires.getDate()+cookieLife);
return expires.toGMTString();
}
The date calculation in your method does not seem to work correctly.
Edit:
Try this code instead. I think I found the issue.
<script type="text/javascript">
function getCookie(w){
cName = "";
pCOOKIES = new Array();
pCOOKIES = document.cookie.split(';');
for(bb = 0; bb < pCOOKIES.length; bb++){
NmeVal = new Array();
NmeVal = pCOOKIES[bb].split('=');
if(NmeVal[0] == w){
cName = unescape(NmeVal[1]);
}
}
return cName;
}
function printCookies(w){
cStr = "";
pCOOKIES = new Array();
pCOOKIES = document.cookie.split(';');
for(bb = 0; bb < pCOOKIES.length; bb++){
NmeVal = new Array();
NmeVal = pCOOKIES[bb].split('=');
if(NmeVal[0]){
cStr += NmeVal[0] + '=' + unescape(NmeVal[1]) + ';';
}
}
return cStr;
}
function setCookie(name, value, expires, path, domain, secure){
var cookie = name + "=" + escape(value);
if(expires){
expires = setExpiration(expires);
cookie += ";expires=" + expires;
}
if(path){
cookie += ";path=" + path;
}
if(domain){
cookie += ";domain=" + domain;
}
if(secure){
cookie += ";secure";
}
document.cookie = cookie;
}
function setExpiration(cookieLife){
var expires = new Date();
expires.setDate(expires.getDate()+cookieLife);
return expires.toGMTString();
}
</script>
<script language="JavaScript">
// set a cookie which will expire in 3 days and be accessible site wide
setCookie('drunkdriving_cta_overlay', 'Yes', 3, '/');
</script>
<script language="JavaScript"><!--
document.write(getCookie("drunkdriving_cta_overlay"));
//-->
</script>

Categories

Resources