Context
I have a form with three inputs (name, password, confirm password), that I want to validate with Javascript for certain criterias (e. g. minimum length of password, etc.). So I created the function validateForm() that does that.
One criteria is that the username shouldn't exist already. So I created the function userExists() (see below), that is called by validateForm(). userExists() works fine on its own, because it logs "Exists" or "Does not exist" correctly in the console.
The Problem and Question
However I cannot get the value wether the userExists (true/false) from the userExists() function to the validateForm() function.
So my question is: How do I get the info, if the User already exists from userExists() to validateForm()?
I am new to Javascript and have been sitting on this issue for literrally a day now. I don't know how to solve this and would be really very grateful for some help.
What I have tried so far
I added return true; and return false; beneath the console.log("Exists / Does not exist"), but when i then call userExists() in validateForm() I dont't get a true or false value (it is "undefined").
I already tried a lot with solutions that refer to the function being asynchronos, (see How to return the response from an asynchronous call), like solving it with a boolean variable that saves the value, Callbacks, timeout and await (which it says in the editor I am not allowed to use in this case) and other suggestions , but that didn't solve it either.
function validateForm() {
//some code
//get true/false of the function userExists() and give according alert (userExists() is undefined, doesn't work)
else if(userExists()){
alert("The name is already in use");
name = "";
return false;
}
//some code
}
function userExists() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 204) {
//logs correctly in the console but doesn't return a boolean
console.log("Exists");
return true;
} else if (xmlhttp.status == 404) {
console.log("Does not exist");
return false;
}
}
}
xmlhttp.open("GET", "#someLink", true);
xmlhttp.send();
}