return value from onreadystatechange with callback
<p>I'm trying to return a value from an onreadystatechange AJAX call... I found this page : <a href="https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function?lq=1">stackoverflow link</a>. I though I had it working but realised that it made no difference to add or remove the fn function. The following code works :</p>

<pre><code>username_is_available();

function username_is_available() {
  var username = document.getElementById('username').value;

  get_data('username', username, function(returned_value) {
   if (returned_value == 'true') {
     document.getElementById('username_err').innerHTML = 'Taken';
    } else {
     document.getElementById('username_err').innerHTML = 'Available';
    };
  });
}

function get_data(data_type, data, fn) {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {
    fn(xmlhttp.responseText);
  }
};
  xmlhttp.open("GET", "availability.php?" + data_type + "=" + data, true);
  xmlhttp.send();
}
</code></pre>

<p>It all works fine but that's not my goal, I would like a function username_is_available() that returns true if the username is indeed available.
Instead, here I an action happens (innerHTML is changed). And if I try and do a return in the anonymous function I get the same result as if I had returned it from directly inside the onreadystatechange : var unasigned</p>