Joe
Joe

Reputation: 8262

How to catch XMLHttpRequest onreadystatechange function result?

I want to catch the returned value of eAC_callback if it was false or true when eAC calls it during onreadystatechange. Can I do that? How?

function eAC(emailData) {
    if (window.XMLHttpRequest) {
        httpRequest = new XMLHttpRequest();
    }

    if (!httpRequest) {
        return false;
    }

    var fd = new FormData();
    fd.append("email", emailData);

    httpRequest.onreadystatechange = eAC_callback;
    httpRequest.open('POST', "http://example.com/p_PEC.php");
    httpRequest.send(fd);
}

eAC_callback returns true or false when readyState is 4 and status is 200

function eAC_callback() {
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
            var response = JSON.parse(httpRequest.responseText);
            if(response.error === 0){
                return true;
            } else {
                if(response.error === 1){
                    return false;
                }
                if(response.error === 2){
                    return false;
                }
            }       
        } else {
            return false;
        }
    }
};

Upvotes: 0

Views: 1078

Answers (1)

Bergi
Bergi

Reputation: 664307

I want to catch the returned value of eAC_callback

Then you will have to wrap it in another function:

httpRequest.onreadystatechange = function() {
    if (eAC_callback()) {
        …
    } else {
        …
    }
};

However, you will never be able to return any results computed in the asynchronous callback to the eAC function that installed the callback (long ago). See also How do I return the response from an asynchronous call? - supply a callback or return a promise.

Upvotes: 1

Related Questions