My goal is to extract symbol names from a stocks API and compare them with the symbol entered in an HTML input field. I am aiming to receive a simple boolean value indicating whether the symbol was found or not, which I have implemented within the request.onload method. However, when I try to retrieve the response from another function, I either get 'undefined' or text resembling an object.
To address this issue, I have included a "load" event listener inside the button click listener. I have experimented with placing the boolean variable inside the request.send method as well as adding a ready state change listener, but none of these approaches have successfully returned the boolean value from the onload method.
const searchInput = document.getElementById("symbol-search-input");
const symbolSearchBtn = document.getElementById("symbol-search-btn");
const symbolSearchMsg = document.getElementById("symbol-status-msg");
const request = new XMLHttpRequest();
symbolSearchBtn.addEventListener("click", () => {
//Value from html input
let symbolSearch = searchInput.value;
if(symbolSearch == "") {
symbolSearchMsg.innerHTML = "symbol field blank";
} else {
//calling XMLHTTPRequest to begin the process
symbolFound();
request.onreadystatechange = () => {
if(request.readyState == 4) {
if(request.status == 200) {
//Below it only returns the entire JSON as text even if I only use "request.response"
console.log(request.responseText);
}
if(request.status == 404) {
console.log('File or resource not found');
}
}
};
let symbolFound = () => {
request.open('GET', 'https://api.iextrading.com/1.0/ref-data/symbols', true);
let foundSymbol = false;
request.onload = function() {
let data = JSON.parse(this.response);
if(request.status >= 200 && request.status < 400) {
let symbolInput = searchInput.value.toUpperCase();
for(let i = 0; i < data.length; i++) {
if(data[i]['symbol'] === symbolInput) {
foundSymbol = true;
break;
}
}
return foundSymbol;
} else {
console.log("error");
}
};
request.send();
};
Despite expecting a boolean result (true or false), the output I am currently receiving is the JSON data from the API displayed as text/string.