0
I am trying to save a user’s name through cookies, but for some reason these cookies are not saved. I am using tutorial of W3schools, but even creating my code like theirs, it doesn’t work.
Here is my label:
<div id="jogador">
<h3>Bem vindo ao jogo da memória da Familia Addams!</h3>
<h4>Digite seu nome para começar</h4>
<input id="nome-usuario" type="text" placeholder="Digite seu nome">
<input type="button" value="Começar" onclick="iniciar()">
</div>
Before the body closes I care:
<script src="JS/jogoMemoria.js"></script>
The cookie manipulation functions are:
// Função para setar o nome do usuario nos cookies
function setCookies(cookieName, cookieValue) {
var expires = "expires=Thu, 01 Jan 1970 00:00:00 UTC";
document.cookie = cookieName + "=" + cookieValue + "; " + expires + "; path=/";
}
// Função para obter os cookies
function getCookies(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
// Função do botão começar
function iniciar() {
var nomeUsuario = document.getElementById("nome-usuario");
setCookies("username",nomeUsuario.value);
}
While trying to make console.log(getCookies("username"))
the return is Undefined. What I may be doing wrong?
Matheus, what URL are you using in the browser? It’s like
http://localhost
? Or is it likeC:\nome da pasta\nome do arquivo.html
?– Leonardo Getulio
Type C: name of the folder name of the.html file.
– MatheusEdnei
The browser does not save a cookie for local html files. You must go up a server like apache or Nginx, has the xampp or wampp suite that is very simple, configure a server of these that will work. When you get out of
file://c:\xyz.html
forhttp://xyz
it will manipulate the cookies right.– Leonardo Getulio
Thank you! That solved the problem.
– MatheusEdnei