I'm facing an issue with my code where the function that worked perfectly for register and login is not functioning properly on the index page.
Even though there seems to be no errors in the login and register functions, I have a form with an input set to submit connected to a variable which listens for events.
Here is an example of my TypeScript login code:
loginForm.addEventListener("submit", async (event) => {
event.preventDefault(); // Prevent the default form submission behavior
// Remove error message if it exists
document.getElementById("error")?.remove();
// Get form data
const formData: FormData = new FormData(loginForm);
const formDataObject: { [key: string]: string } = {};
// Convert formData to a JavaScript object
formData.forEach((value, key) => {
formDataObject[key] = value as string;
});
const username: string = formDataObject["username"];
const password: string = formDataObject["password"];
try {
const rows: any = await api.queryDatabase("SELECT * FROM user WHERE username = ? AND password = ?",
[username], [password]);
// If query returns any result, then log in
if (rows[0]) {
const user: any = rows[0];
session.set("userId", user.userId);
url.redirect("index.html");
} else {
// Throw wrong username or password error
throw new Error("Wrong username or password");
}
}
catch (reason: any) {
// Create error message in login-popup
const errorContainer: any = document.createElement("div");
errorContainer.id = "error";
const errorMessage: any = document.createTextNode(reason);
errorContainer.appendChild(errorMessage);
document.getElementById("login-popup")?.appendChild(errorContainer);
}
});
}
I tried implementing the same logic for the index using a navbar and anchor instead of a submit tag, but now it's not working.
TypeScript code:
function logout(): void{
console.log(session.get("userId"));
//const unorderedList: HTMLUListElement = document.getElementById("navlist") as HTMLUListElement;
const logoutButton: HTMLAnchorElement = document.getElementById("logout") as HTMLAnchorElement;
logoutButton.addEventListener("click", async (event) =>{
console.log("Clicked logout button");
event.preventDefault(); // Prevent the default form submission behavior
session.remove("userId");
url.redirect("index.html");
});
}
logout();
The first console log does return the user ID in the console, indicating a successful connection with the database.
HTML code:
<li class="hidden" id="logout"><a type="logout" id="logout" href="" >Logout</a></li>
I have tried various changes in variable types, IDs, positions, and names, but unfortunately, none seem to resolve the issue.