Probably I’m thinking the wrong way, I wanted to write reusable code, so for example I brought out a common routine to make small functions instead of a big nested one.
$user = document.getElementById("newuser-name").value;
if (validateUser($user) == true){
//do something
} else {
//do something else
}
This is my my code inside a button click event, the user enter some user name and submit for validating it (already taken?) on my endpoint. So far so good, but I cannot receive the return value from my validateUser
function:
function validateUser($user){
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents; //this return should return as validateUser
httpRequest.open('POST', 'https://www.example.com/myendpoint.php');
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.send('user=' + $user);
function alertContents() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
if (this.responseText == 'X'){
return false;
} else {
return true;
}
}
}
}
The problem is I cannot “pierce” the alertContents
function and make its returned value reflect as a return value for validateUser
. Do I need to necessarily nest all that into my button click event? What if I need to re-use this code? For example if the user wants to change user name, do I need to duplicate the same code in another click event? How do I make this reusable, calling a function which returns a value?