0

I have the following code:

function loadXMLDoc() {

        var xhr = XMLHttpRequest();
        xhr.onreadystatechange = function () {
            //read the file and get results
            getDomicilesFromXML(xhr); //separate function (this is not the problem)

        };
        xhr.open('GET', TheXMLFile.xml', false);
        xhr.send();

    }

This function is called in the initialize function for the web page. "TheXMLFile" is an XML file that is in the root project directory of my website. It doesn't seem to be reading the file, as the result is always null. Am I missing something?

2
  • I´m not sure if that is async or not, but why is the alert before the send? Commented Jan 28, 2016 at 17:21
  • Oh, sorry. I was just testing something. It failed, of course. I'll take it out. Commented Jan 28, 2016 at 17:22

1 Answer 1

1

onreadystatechange is fired repeatedly several times before the response is ready to be read. You need to check xhr.readyState to see whether it's ready, and status to see whether it was successful.

xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status == 0 || (xhr.status >= 200 && xhr.status < 300)) {
            //read the file and get results
            getDomicilesFromXML(xhr); //separate function (this is not the problem)
        }
    }
};

(The xhr.status == 0 is a workaround I'm not sure we still need these days, some browsers [used to?] do that with cached responses.)


I would recommend removing the false from your open call. Forcing the HTTP request to be synchronous is almost never necessary, and locks up the UI of the browser during the request.

Sign up to request clarification or add additional context in comments.

1 Comment

I believe this worked; however, I'm getting another error now. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.