Javascript method with XMLHttpRequest returning undefined

1528 views javascript
3

I have the following method that should return either true or false:

theMethod() {
    const httpRequest = new XMLHttpRequest();
    httpRequest.open("GET", 'http://someurl.com', true);
    httpRequest.send();
    httpRequest.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        return true;
    } else {
        return false;
    }
    };
}

In both cases it's returning 'undefined'

How can I fix this?

answered question

Only the anonymous function is returning true/false, theMethod is not returning anything. And the function itself won't execute whenever you call theMethod. True would have to be returned in future. Plus I think onreadystatechange is assigned before send(). You should pass two functions to the method and call them instead of returning true or false. Also see stackoverflow.com/questions/14220321/…

1 Answer

10

thisMethod will always return undefined, because it has no return statement in it. All it does is make an Ajax request, which of course is asynchronous - it will only complete after thisMethod has returned. (Or hasn't, as the case is here.)

You attached a callback function to that Ajax call - as is normal, indeed required in order to be able to do anything with the results. That function is the one which returns either true or false to indicate whether the Ajax succeeded or not. But thisMethod itself doesn't return anything.

Note that your callback which just returns a value won't actually have any observable effect - because you are not doing anything with the return value. Typically you don't with a callback like this, you just do something with the response (typically render it on the page somewhere, or log it to the console).

posted this

Have an answer?

JD

Please login first before posting an answer.