Is there a way to send a personalized reply from an XMLHttpRequest?

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.

Answer №1

After some tinkering, I managed to find a solution - a workaround of sorts. Instead of simply returning a value, I opted to change the state of a variable and then called another function to manipulate the boolean as needed. It also involved breaking down the initial function. Take a look.

const searchInput = document.getElementById("symbol-search-input");
const symbolSearchBtn = document.getElementById("symbol-search-btn");
const symbolSearchMsg = document.getElementById("symbol-status-msg");
let isSymbolFound;


symbolSearchBtn.addEventListener("click", () => {

    let symbolSearch = searchInput.value;

    if(symbolSearch == "") {
        symbolSearchMsg.innerHTML = "symbol field blank";

    } else {
        isSymbolFound = false;
        const xhr = new XMLHttpRequest();
        xhrProcess(xhr);

        xhr.onload = function() {
            let data = JSON.parse(this.response);

            if(xhr.status >= 200 && xhr.status < 400) {
                let symbolInput = symbolSearch.toUpperCase();

                for(let i = 0; i < data.length; i++) {
                    if(data[i]['symbol'] === symbolInput) {
                        isSymbolFound = true;
                        break;
                    }
                }
                symbolFindProcess();

            } else {
                console.log("error");
            }
        };
    }
});

const symbolFindProcess = () => {
    if(isSymbolFound) {
        //code here
    } else {
        //code here
    }
};

const xhrProcess = (request) => {
    request.open('GET', 'https://api.iextrading.com/1.0/ref-data/symbols', true);
    request.send();
};


Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to dynamically generate a card using NuxtJS

I'm just starting out with NuxtJS and I'm curious about how to generate a v-card within a v-dialog box. Imagine this scenario: I have an "add" button that triggers a v-dialog, where I can input information into a form. After submitting the form, ...

Adjust size of element in relation to Background Cover using jQuery

Can you help me solve a challenge I'm facing? I have a website with a fullsize background image, and I need to attach a div to a specific position on the image while ensuring that it scales in the same way as the background image with the "background ...

The Angular material datepicker is not accurately capturing the date I am trying to select

I am facing an issue with the Angular Material datepicker where it does not select the date I choose. Instead, in my AngularJS controller, I always get the sysdate even if I select another date. Can anyone help me figure out what I am doing wrong? Here is ...

Add information in the JSON structure

I am trying to display some JSON data in a div, but the current code is not working. Can anyone suggest where I should make changes? <div class="risktable"> </div> $.ajax({ contentType:'application/json', data: {"sp ...

Tips for transforming an Observable stream into an Observable Array

My goal is to fetch a list of dogs from a database and return it as an Observable<Dog[]>. However, whenever I attempt to convert the incoming stream to an array by using toArray() or any other method, no data is returned when calling the retrieveDo ...

Utilize Jquery Loop to Showcase JSONP Array

I've gone through a multitude of similar questions, attempted to implement the solutions provided but still can't quite seem to make it work. I'm pretty sure it's just a simple mistake since I'm new to this. I have removed the URL ...

Is there a way to ensure that a statement will not execute until the completion of a preceding function?

I am encountering an issue where the window.open function is being called too quickly, causing my other function not to finish and post in time within my onclick event. I attempted to address this by setting a timeout on the trackData() function, but it o ...

A JavaScript function that yields no value is undefined

In my AngularJS project, I have a function that makes a GET request to the backend multiple times and returns data. Here is an example of how the function is used: function getFunction(inputData) { $http.get('request URL', { params: 'so ...

Is there a way to utilize a cookie in order for the website to recognize that I have already agreed to the terms?

It's common for websites to ask for cookie and privacy acceptance upon loading, especially in the EU. I'm looking for a way to automatically accept these cookies so I don't have to constantly click "accept all" every time I open Chrome. My ...

Ways to block WebSocket access on a personal computer

Is it possible to protect my server resources from being accessed by other websites, such as example.com, via WebSocket? I want to prevent them from accessing the server using a URL like "ws://47.80.151.189:1234", and utilizing its resources (bandwidth, me ...

Substituting placeholders within a docx template remains incomplete

Utilizing this specific library, I am implementing a feature to substitute placeholders within a docx template and generate multiple documents. The technologies involved are neutralino and vue for the front-end, where I have devised a method that transmits ...

Angular 4: Utilizing reactive forms for dynamic addition and removal of elements in a string array

I am looking for a way to modify a reactive form so that it can add and delete fields to a string array dynamically. Currently, I am using a FormArray but it adds the new items as objects rather than just simple strings in the array. Here is an example of ...

The Katura video is loading properly, yet it is rotating instead of playing

I am working on a web application that involves playing videos from Kaltura platform and then loading the link on an iOS webview. <html> <body> <div id="myEmbedTarget" style="width:400px;height:330px;"></div> ...

The attempted JavaScript socket emissions from the server to the client for listening are currently experiencing difficulties and

I have encountered a peculiar issue with my code. It involves emitting from the server side and listening on the client side. The connection seems to persist indefinitely, even when the client refreshes or exits the page. However, the code on the client si ...

Can a software be created to capture search results from the internet?

Is it feasible to create a program that can extract online search results? I am specifically interested in retrieving data from Some of the data I need include application numbers, such as 9078871 and 10595401 Although there are CAPTCHAs present, I am w ...

how to combine a string in JavaScript using a prefix and suffix

Anion Gap Body Surface Area (BSA) Creatinine Clearance Stack Overflow i want to add "String" Before Text and "String" after end of text. I have Following expression which runs perfectly in excel:- =CONCATENATE("",B1,"") Output:- <string>Anion Ga ...

A continuous jQuery method for updating select option values

I'm currently working on a form and using jQuery to make some alterations. The form consists of multiple select elements, and I want to change the value of the first option in each of them. However, as the form allows for dynamic addition of new selec ...

Cannot close the Bootstrap dropdown after selecting an option

I am encountering an issue with a dropdown list that has a select feature using Bootstrap 3.4.1. The problem is that the dropdown remains open after selection and does not close unless I click outside of the list. Here is the HTML code: <div id="c ...

The callback function in JavaScript is not updating AngularJS unless it is written in shorthand form

Within an angular controller designed for user login functionality, the code snippets below are extracted from an angular-meteor tutorial: this.login = function() { Meteor.loginWithPassword(this.credentials.email, this.credentials.password, (e ...

What is the method for altering the color of the webkit-slider-thumb using JavaScript?

I am looking to adjust the color of an input range using JavaScript instead of CSS. Can someone help me with this request? Current CSS Code: input[type='range']::-webkit-slider-thumb { -webkit-appearance: none; background: goldenrod !importa ...