Accessing the 'httpRequest.onreadystatechange' returned value

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?

Hmm, you return true or false, but why couldn’t you return whatever you want, like an object with properties of interest to the calling function?

it is not returning neither tru/false at this moment.

Seeing XMLHttpRequest brings some unpleasant memories :upside_down_face:.
Anyway, your validateUser doesn’t return any value. The true/false is returned in the event handler.

Also, maybe use fetch instead? The API is much easier to use and reason about.

can you pass the event handler return to the parent function that called it?

Nope, you are running asynchronous operation, so your parent function have to either return a promise or accept a callback.
You can return new Promise(resolve => ...) and then call the resolve inside or even better, use the fetch which already returns a promise.