1

I need help from you.
from the previous case, I'm using JSON object as data storage for the accounts.
The Case is I created cookies from file js named 'login.js'.
Here my code (login.js):

ajaxhttp.onreadystatechange = function () {
    if(ajaxhttp.readyState == 4 && ajaxhttp.status == 200) {
        var jcontent = JSON.parse(ajaxhttp.responseText);
        document.addEventListener("submit", validateForm);
        function validateForm(e) {
            let uName = document.getElementById("username").value;
            let pWord = document.getElementById("password").value;

            const user = jcontent.users.find(r => r.username == uName && r.password == pWord)

            function setCookie(cname, cvalue, exdays) {
                var d = new Date();
                d.setTime(d.getTime() + (exdays*24*60*60*1000));
                var expires = "expires="+d.toUTCString();
                document.cookie = cname + "=" + cvalue + "; " + expires;
            }

            if(user) {
                setCookie("user", JSON.stringify(user), 3);
                alert("Successfully login!")
            }
            else {
                e.preventDefault()
                alert("Username or Password is wrong!");
            }
        }
    }
}

ajaxhttp.send(null);

The cookies are successfully created. But when I directing into index.html with different JS files (named 'index.js' ) I failed to get the cookies.
Here my code (on index.js):

 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 "";
}

var x = getCookie("user");

document.getElementById("getUser").innerHTML = x.first_name;

The document.getElementById("getUser").innerHTML = x.first_name; define when I successfully logged in and direct into dashboard (index.html), it will show a username that I logged in before.

Should I use an import statement?

park_ul
  • 15
  • 6

1 Answers1

1

When you store the data as JSON in the cookie, you use a method called stringify to Serialize the object. So, when you want to get the data back, you need to pass JSON.parse(<JSON String> inside your getCookie() method.

Example:

unction 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 JSON.parse(c.substring(name.length,c.length));
  }
  return "";
}

var x = getCookie("user");

document.getElementById("getUser").innerHTML = x.first_name;
Harshana
  • 5,151
  • 1
  • 17
  • 27
  • Thanks, it works! but why `JSON.parse()` can still read the object without declaring ajax? Sorry, my experience in javascript is still fairly weak. – park_ul Dec 16 '20 at 09:19
  • Ajax comes from Jquery which is a different framework while `JSON.parse()` comes from javascript language itself. – Harshana Dec 16 '20 at 09:21