0

I want to send a request to the server, and return the response using AJAX. I know that a good method for this is using a callback, however I am curious why xHTTP.onreadystatechange = function(){ ... } can't access _response variable.

function __GET(url)
{
    var _response;
    var xHTTP = new XMLHttpRequest();

    xHTTP.open("GET", url, true);
    xHTTP.onreadystatechange = function(){
        if (xHTTP.readyState == 4){
            _response = JSON.parse(JSON.stringify(xHTTP.responseText));
        }
    };
    xHTTP.send();

    return _response;
}
default
  • 106
  • 2
  • 10
  • I am aware of that topic. My request/response works perfectly, however my big question is why `xHTTP.onreadystatechange = function(){ ... }` doesn't modify `_response` variable. – default May 19 '17 at 13:45
  • why dont you return _response from inside `readyState == 4`. Its async. _response will be returned before xHTTP is done. – Stephen Tetreault May 19 '17 at 13:57

0 Answers0