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?