Similar Questions
Similar questions that I have already tried to apply to my case, but didn't lead to the conclusion of this problem. If you have a similar problem however, these might be worth looking into:
- How to return the response from an asynchronous call
- Return value from AJAX onreadystatechange Event
- return value from onreadystatechange with callback
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
However, I struggle hard to get a boolean (true/false) with the function userExists() in the function validateForm().
I identified two issues that make this difficult:
- Getting the value out of the onreadystatechange property
- asynchronous functions: Making validateForm() wait for userExists() to finish before continuing (which I tried to solve via callback)
The Question
How do I get the info, if the User already exists from userExists() to validateForm()?
I am new to (and a little overwhelmed by) Javascript and have been sitting on this issue for literrally two days now. I am not sure if there is a structural problem or if it is just a little syntax error. I don't know how to solve this and would be really very grateful for some help.
Code
var val;
var exists;
var performSomeAction = function (exists) {
val = exists;
}
function validateForm() {
const name = document.getElementById("username").value;
//checking some inputs
//check if the username is already in use
console.log(nameExists);
else if (nameExists) {
alert("The name is already in use");
name = "";
return false;
}
//validating more inputs
}
function userExists(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 204) {
console.log("Exists");
callback(true);
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 404) {
console.log("Does not exist");
callback(false);
}
};
xmlhttp.open("GET", "#aLinkThatIsNotTheIssue", true);
xmlhttp.send("");
}
Result
The current output in the console is:
undefined
Exists