manisha manisha - 19 days ago 6
Javascript Question

AJAX don't understand order of events in this example

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

i think you should be checking your readyState values with the actual values of the response. For you reference, following are the possible values of readyState:

0: request not initialized 
1: server connection established
2: request received 
3: processing request 
4: request finished and response is ready

So you could basically check it to be 4 in your case:

var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState === 4) {
            //response statements
        } else {
            //error statements
        }
    };