0
I’m an information systems student and I’m learning how to create cookies in javascrit using functions and webstorege, but I’m having trouble creating the function to check if a cookie has been recorded or not.
Look at the code:
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays){
var d = new Date();
d.setTime(d.getTime()+(exdays*60*60*24*365));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires +";paths=/";
alert("cookie inserido com sucesso");
}
function getCookie(cname, cvalue, exdays){
var d = new Date();
d.getTime(d.getTime()+(exdays*60*60*24*365));
var expires = "expires" + d.toUTCString();
document.cookie = cname +"=" + cvalue + ";" + expires + ";paths=/";
alert("Cookie exibido");
}
function checCookie(cname, cvalue, exdays){
var d = new Date();
d.getTime(d.getTime()+(exdays*60*60*24*365));
var expires = "expires" + d.toUTCString();
document.cookie = cname +"=" + cvalue + ";" + expires + ";paths=/";
alert("Cookie exibido");
}
function apagarCookie(cname, cvalue, exdays){
var d = new Date();
d.getTime(d.getTime()+(exdays*60*60*24*365));
var expires = "expires" + d.toUTCString();
document.cookie = cname +"=" + cvalue + ";" + expires + ";paths=/";
alert("Cookie exibido");
}
</script>
</head>
<body>
<center>
<h1>Testes de Cookies</h1>
<button id="btncookie" onclick="setCookie()">Gravar Cookies</button>
<button id="btnExibir" onclick="getCookie()">Exibir Cookie</button>
</center>
</body>
</html>
What’s wrong with the checkCookie function?
How can I correct this mistake?
I believe Cookie is only verifiable after page reload, but I may be wrong.
– Sveen
I don’t know if you’d be willing to change, but try using localStorage in Javascript as it’s safer and easier to use.
– Sveen