Clarification on the order and frequency of AJAX XHR request onReadyStateChange events

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();
} 

Answer №1

The response is not showing distinct HTTP status codes; instead, it is displaying various ready states.

Try replacing console.log("ERROR"); with console.log(request.readyState);.

This will provide insight into the reported information and its significance.

Answer №2

It would be beneficial for you to compare the readyState values with the response's actual values. Here are the potential readyState values for your reference:

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

In your situation, you can specifically check if it equals 4 like this:

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

Answer №3

When making ajax calls, the readyStateChange event notifies for various events.

https://i.sstatic.net/1dWI2.jpg

In most scenarios, there are 4 ready state changes depending on the connection speed (sometimes only one if it's very fast), and you need to verify if it is 4, indicating that the response is complete.

To determine whether the request was successful, check if request.status === 200 which signifies success, or look out for other http status codes like 404, 500, etc., for errors.

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" />

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

How can I stop an element from losing focus?

One issue I'm facing is that when I have multiple elements with the tabindex attribute, they lose focus when I click on any area outside of them. The Problem - In traditional desktop applications, if an element is not able to receive focus, clicking ...

Creating an extension of a Vue.js component from a third-party library

I'm currently using the ElDatepicker component from element-ui and I am looking to customize its template and event handler method. I have attempted to achieve this within a single file component: import Vue from 'vue'; import ElDatePicker ...

Displaying a Modal with a Click Action

I am encountering a challenge in displaying a modal when clicked using onClick(). In a component, I have a function that adds players to a list when the Add Player button is clicked. This button is generated separately in a function called renderAddButton( ...

Exploring the use of the "++" operator in Regular

Is there a way to detect the presence of ++, --, // or ** signs in a string? Any help would be greatly appreciated. var str = document.getElementById('screen').innerHTML; var res = str.substring(0, str.length); var patt1 = ++,--,//,**; var resul ...

Looping through a collection of JSON objects without a parent element

Utilizing jQuery UI Autocomplete, I have encountered a situation where the documentation mentions that the source can consist of a list of JSON objects. The current code is functional; however, it lacks a root element for the list of JSON objects. <scri ...

Leverage the power of JSON to efficiently represent a collection of string

Currently, I am engrossed in reading the 3rd edition of JavaScript Pocket Reference. The author makes an interesting statement in chapter 5 - Objects on page 75: In JavaScript, objects are dynamic, allowing properties to be added and deleted at will. Int ...

"Utilize AJAX to submit user feedback ratings to the database - Like or Dis

I'm facing a slight issue - I am trying to send an ajax request to a specific file. Let's take a look at my HTML File (index.html) <a id="like" href="./?act=like&id=24" title="Nobody likes this post!">Like</a> &middot; <a ...

When restarting the React application, CSS styles disappear from the page

While developing my React application, I encountered a problem with the CSS styling of the Select component from Material UI. Specifically, when I attempt to remove padding from the Select component, the padding is successfully removed. However, upon refre ...

Sending a function as a callback to children components in order to update a specific child component

I am currently working on developing a Navbar component that undergoes slight changes when a user logs in through a SignIn component. Here is an overview of how my application is structured: Initially, I have defined a state in the App component where aut ...

Comparison between UI Router and ngRoute for building single page applications

Embarking on a new Angular project, a single page app with anticipated complex views such as dialogs, wizards, popups, and loaders. The specific requirements are yet to be clarified. Should I embrace ui.router from the start? Or begin with ngRoute and tra ...

Exploring the shapes and dimensions of a truncated Icosahedron in preparation for graphic design purposes

I am attempting to create a truncated icosahedron design with interactive clickable areas using Three.js. Initially, I came across code for a standard icosahedron: var t = ( 1 + Math.sqrt( 5 ) ) / 2; var vertices = [ [ -1, t, 0 ], [ 1, t, 0 ], [ ...

implement CSS styles within a JavaScript function

I am trying to change the background every second with the following code, but I am having trouble including CSS properties like centering, covering, and positioning the image properly. How can I modify this function to incorporate these settings for the ...

Combine various input data and store it in a variable

I am looking for a way to add multiple input text values together and store the sum in a variable. Currently, I can add the values and display it in an id, but I want to assign it to a variable instead. The condition for this variable is described below af ...

Looking for the time trigger feature in jQuery using typeahead search?

Is there a way to trigger an event every 3 seconds in Laravel Vue.js? I am currently using jQuery in my script. The issue is that when I type something in the search input field, the event is triggered after each character I type. What I want is for the ev ...

Manipulate JSON data using a string path in JavaScript

Suppose I have the following JSON data, which can easily be converted into a JavaScript object: { "foo": { "bar": "Common substitute word", "baz": "Another common substitute word", "questionWords": { "wat": "Inadequ ...

How can we universally detect and resolve the user's language within a React/Next.js application using an Apollo client HOC?

Currently, I am developing an I18n module utilizing the Next.js framework (v5). The challenge I am facing is determining the user's default language universally in order to display the UI in that language. While it is relatively simple to resolve th ...

Navigating Through Objects

Currently, I am utilizing the Jquery Dropdown Plugin and ListJS Plugin for my project. The jQuery Dropdown Plugin features a hide event: $('.dropdown').on('hide', function(event, dropdownData) { }); Within this event, I am integratin ...

Complete a form when a link or button on the webpage is clicked

I have a variety of links and buttons on my webpage, and they are generated dynamically. I am unable to assign an onclick event to each one individually. My goal is to submit form data to the next page whenever any link or button on the page is clicked. ...

Learn the process of connecting checkboxes to a database in MeanStack using Angular

Hey everyone, I'm currently working with AngularJS ng-repeat and I am trying to dynamically bind a checkbox based on a true or false value from the database. However, even when the database value is set to true, the checkbox does not automatically che ...

Tips for avoiding deleting content within a span element when using contenteditable

I am working on an HTML 5 editor that utilizes the contenteditable tag. Inside this tag, I have a span. The issue arises when all text is removed as the span also gets removed. I want to prevent the removal of the span, how can I achieve this? Here is a s ...