Currently, I am in the process of learning how to create a basic stock quote tool using Python-Flask and Javascript.
I have a specific interest in mastering plain Javascript. While my code is functional, I am puzzled by the fact that I receive 3 error messages in the developer console before finally seeing the successful console.log(response).
Could this be due to the code running through a loop 3 times before receiving the response, resulting in 'ERROR' being logged each time until the 200 status is returned? If anyone could provide an explanation or point me towards a helpful article/post on this topic, it would be greatly appreciated.
Here is the event listener I am using:
document.getElementById("btn_quote").addEventListener("click", getQuote);
The ajax call being made:
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();
}