manisha manisha - 10 days ago 5
Ajax Question

AJAX XHR request onReadyStateChange events order and number of times clarification

I'm learning and trying to write a simple stock quote tool using Python-Flask and Javascript.

I specifically want to learn plain Javascript. My code is working, but what I don't understand is when I'm watching the developer console, I get 3 error messages printed before I get the successful console.log(response).

Is it simply that the code loops 3 times before the response comes back, so it logged 'ERROR' each of those times before finally returning the 200 status? Would someone explain it to me or point me to a good article/post?

My event listener:

document.getElementById("btn_quote").addEventListener("click", getQuote);


The ajax call:

function getQuote(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value
var shares = document.getElementById("shares").value
var url = "/quote/"+ticker+"/"+shares

// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var response = JSON.parse(request.response);
console.log(response);
}
} else {
// TODO, handle error when no data is available.
console.log('ERROR');
return false;
}
};
request.open('GET', url);
request.send();
}

Answer

Basically, ajax calls will get notified for the following events which is called as readyStateChange event.

enter image description here

For most cases, you used to get 4 ready state changes based on the speed of the connection (rare cases only only one if it's very quick) and you should check whether it is 4 which means the response is completed now.

To check whether the request is suceess or not, you should check the request.status === 200 which means success and can check for other http status code for errors like 404, 500 etc.

document.getElementById("btn_quote").addEventListener("click", getQuote);
document.getElementById("btn_quote_error").addEventListener("click", getQuoteError);

function getQuote(e){
    e.preventDefault();
    var ticker = document.getElementById("ticker").value;
    var shares = document.getElementById("shares").value;
    //var url = "/quote/" + ticker + "/" + shares;
    var url = 'http://stackoverflow.com/';

    // Fetch the latest data.
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
      console.log(request.readyState);
        if (request.readyState === XMLHttpRequest.DONE) {
            console.log(request.status);
            if (request.status === 200) {
                //var response = JSON.parse(request.response);
                //console.log(response);
            }
        } 
        //else {
            // TODO, handle error when no data is available.
            //console.log('ERROR');
            //return false;
        //}
    };
        request.open('GET', url, true);
        request.send();

  
}

function getQuoteError(e){
    e.preventDefault();
    var ticker = document.getElementById("ticker").value;
    var shares = document.getElementById("shares").value;
    //var url = "/quote/" + ticker + "/" + shares;
    var url = 'http://stackoverflow404.com/';

    // Fetch the latest data.
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
      console.log(request.readyState);
        if (request.readyState === XMLHttpRequest.DONE) {
            console.log(request.status);
            if (request.status === 200) {
                //var response = JSON.parse(request.response);
                //console.log(response);
            }
        } 
        //else {
            // TODO, handle error when no data is available.
            //console.log('ERROR');
            //return false;
        //}
    };
        request.open('GET', url, true);
        request.send();

  
}
<input type="text" id="ticker"/>
<input type="text" id="shares"/>
<input type="button" id="btn_quote" value="Get Quote" />
<input type="button" id="btn_quote_error" value="Get Quote Error" />

Comments