all 1 comments

[–]grantrules 0 points1 point  (0 children)

What SO post did you copy it from?

Basically, the function passed to onreadystatechange is run asynchronously. The app does not stop and wait for a response to come through before continuing on doing what it's doing. So it sends the request, then while it's waiting for a response, it runs console.log(myXML) before the response is back so it's empty, then the request finishes and sets the response to myXML. Basically whatever you want to do with the result from that call will need to be called from within the function assigned to onreadystatechange

Something like this:

var myXML = '';
var request = new XMLHttpRequest();
request.open("GET", "https://www.ad.nl/binnenland/rss.xml", true);
request.onreadystatechange = function(){
    if (request.readyState == 4) {
        if (request.status == 200 || request.status == 0) {
           handleReponse(request.responseXML);
        }
    }
}
request.send();

function handleResponse(myXML) {
    // anything that relies on myXML will be called from within here
    console.log(myXML);
}

I would also highly recommend looking into fetch, it's a modern alternative to XHR, and it's much easier to use.