Cookies not saved - Javascript

Asked

Viewed 87 times

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 like C:\nome da pasta\nome do arquivo.html?

  • Type C: name of the folder name of the.html file.

  • 1

    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 for http://xyz it will manipulate the cookies right.

  • Thank you! That solved the problem.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.