Abaan Shanid
Abaan Shanid

Reputation: 472

Can't set localStorage

I have made a login system to verify the password with the username. This is my code:

function verify(e) {
  $("#loginError")[0].innerHTML = ("Name and password must have a value");
  $("#loginError")[0].style.display = "none";
  if ($("#loginName")[0].value != "" && $("#loginPassword")[0].value != "") {
    e.classList.add('loading');
    e.disabled = true;
    var json = {
      name: $("#loginName")[0].value,
      password: $("#loginPassword")[0].value
    };
    e.classList.add('disabled');
    $.get('https://cloud.abaanshanid.repl.co/verifyacc', json, function(data, textStatus, jqXHR) {
      console.log(data);
      if (data.includes("name") == true) {
        e.classList.remove('loading');
        e.disabled = false;
        e.classList.remove('disabled');
        console.log("User there");
        window.localStorage.setItem("loginInfo", data);
      } else if (data == "404") {
        $("#loginError")[0].innerHTML = ("This accout doesn't exist!")
        $("#loginError")[0].style.display = "block";
        e.classList.remove('loading');
        e.disabled = false;
        e.classList.remove('disabled');
      } else {
        $("#loginError")[0].innerHTML = ("Wrong password!")
        $("#loginError")[0].style.display = "block";
        e.classList.remove('loading');
        e.disabled = false;
        e.classList.remove('disabled');
      }
    });
  } else {
    $("#loginError")[0].style.display = "block"
  }
}
After the request the server returns the user data if the password is correct, I want to save the user info in localStorage, but I can't save the data for some reason. The browser doesn't show any errors either.

Upvotes: 0

Views: 902

Answers (1)

AllWorkNoPlay
AllWorkNoPlay

Reputation: 21

Local storage can only have strings, if you need to set "data" then you have to parse it, try: window.localStorage.setItem("loginInfo", JSON.stringify(data));

You can read it back with JSON.parse(window.localStorage.getItem("loginInfo")).

Hope this helped!

Upvotes: 2

Related Questions