Readiness of Ajax onreadystatechange function state

I have a script that fetches raw JSON data for an image from Flickr and displays it on the page. I want to provide real-time feedback using readyState during the process.

Currently, my code checks if the readyState is 4 and the status is 200 before adding the JSON data to the page.

Sample Code:

function sendRequest (request) {

   //Request contains tags entered by the user to search images on Flickr.

    x = new XMLHttpRequest();
    x.open("GET", request,false);
    x.send(null);

    if (x.readyState==4 && x.status==200)
    {
        document.getElementById("resultsContainer").innerHTML="Raw JSON Data: <br>"+x.responseText+"<br><br>";
    } 
}

The received value is added to the resultsContainer div. I also attempted to provide feedback in the same div like this:

if(x.readyState==3){
    document.getElementById("resultsContainer").innerHTML="Processing Request";
}

However, the feedback did not show up. Why does it recognize ready state 4 but not 3?

I tried using the onreadystatechange function but it didn't work as expected. How can I update the UI while the request is ongoing (readyState == 3)?

UPDATE:

UPDATED CODE:

function sendRequest (request) {

    x = new XMLHttpRequest();
    x.open("GET", request,true);
    x.send();

    x.onreadystatechange = function () {

        if (x.readyState==4 && x.status==200){
            document.getElementById("resultsContainer").innerHTML="success <br>"+x.responseText;
        } 

        if(x.readyState==3){
            document.getElementById("getIms").value="Processing";
        }

    }
}

The value of element getIms changes to "Processing" only when the response is received and displayed in the results container.

Answer №1

In order to improve your code efficiency, it is recommended to make the following changes:

x.open("GET", request, true);
x.onreadystatechange = function()
{
    //Custom code implementation for handling readyState==4 and readyState==3
    if (x.readyState==4 && x.status==200)
    {
        document.getElementById("resultsContainer").innerHTML="Raw JSON Data: <br>"+x.responseText+"<br><br>";
    }
    else if (x.readyState==2)
    {
        document.getElementById("resultsContainer").innerHTML="Processing Request";
    }
}
x.send();

The reason for this adjustment is that setting 'false' in x.open causes synchronous behavior, meaning the request is sent and waits until a response is received before continuing with the code execution.

By changing it to asynchronous mode and adding an event handler for readyState changes, the code will be more responsive and flexible.

Make sure to include any processing logic within an else-statement to handle operations while the request is being processed. The absence of action on readyState=3 is due to its short duration when only a small amount of data has been received. readyState=2 indicates that the request has been successfully sent.

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

Diving deep into the reasons behind a test's failure

Currently, I am using Postman to test the API that I am developing with express. In this process, I am creating a series of tests. Below is a brief example: tests["Status code is 200"] = responseCode.code === 200; // Verifying the expected board var expe ...

Centering an image that is absolutely positioned within a container that is relatively positioned, horizontally

Looking to center an image that is positioned absolutely horizontally within a container that is relatively positioned. After attempting with CSS and not finding success, I ended up using Jquery. http://jsfiddle.net/CY6TP/ [This is my attempt using Jquery ...

Web application experiencing issues with electron loading and functioning properly

I attempted to load a web application in electron using window.loadurl and as a webview in html. The application is displaying, but encountering various errors such as: $ jquery not defined Uncaught TypeError: $(...).daterangepicker is not a function Unca ...

What is the best way to toggle a d3 svg overlay using a leaflet layer control?

I am looking for a solution to place 3 d3 svgs on a leaflet map and control them as easily as leaflet layers. Check out this code example, which works but is not ideal. The key part is from line 75 onwards, where I create a custom layer control linked to ...

Obtain the Text Content from a Knockout Dropdown Menu

Currently, I am facing an issue with extracting the text value of a selected option from a dropdown menu on my webpage. The dropdown contains various image categories and is defined as follows: <select class="form-control" data-bind="options: imageCate ...

Send the values of the form variables as arguments

I am trying to integrate a webform (shown below) with a function that passes form variables. Once the user clicks submit, I want the username and password to be passed into a website login function: $.ajax( { url: "http://microsubs.risk.ne ...

Concurrent HTTP Requests - AngularJS

My directive, known as machineForm, includes a dataService: dataService.getMachineTaxesById($scope.machineId).then(function (response) { $scope.machine.machineTaxes = response.data; }); I am using this directive twice simultaneously. <div class= ...

Mastering the art of navigating through intricate nested properties within JSON data structures

Presented below is a dynamic JSON structure: data = { "name": "deltha", "type": "object", "important": [ "name", "id", "number" ], "information": { "place": { "editable": false, "visible": true }, "info": { ...

What is the best way to verify and eliminate unnecessary attributes from a JSON request payload in a node.js application?

My goal is to verify the data in the request payload and eliminate any unknown attributes. Example of a request payload: { "firstname":"john", "lastname":"clinton", "age": 32 } Required attributes: firstname and lastname Optional a ...

An error occurs when calling useSWR in a function that is neither a React function component nor a custom React Hook function

When using useSWR to fetch data from an endpoint, I encountered the following error (I only want to fetch data onclick) "useSWR is called in function `fetchUsers` that is neither a React function component nor a custom React Hook function" Error ...

Find common connections on Facebook using an app PRIOR to downloading it

Is there a way to programmatically find mutual friends between myself and an application or page? For instance, in the scenario shown below: In the image above, it's evident that prior to installing the Causes App (1) I can observe that myself and t ...

When React JS and PHP(Mysql) combine, the error message "records.map is not a function" may appear

What problem am I facing with my code? The issue lies in my JavaScript code while trying to display the JSON array fetched correctly by the PHP file. The JavaScript implementation of JSON in the state is accurate, but an error occurs when attempting to us ...

In the Vercel production environment, when building Next.js getStaticPaths with URL parameters, the slashes are represented as %

I've encountered an issue while implementing a nextjs dynamic route for my static documentation page. Everything works perfectly in my local environment, and the code compiles successfully. However, when I try to access the production URL, it doesn&ap ...

Filling in a text field with the text content (rather than the value) from a dropdown menu

Presently, I have the select box with the id "title" populating a text field with the id "costcenter". The current code works perfectly fine when using the VALUE of the select box to trigger the population of the cost center field. However, my requirement ...

Incorporate a stylish gradient background into react-chartjs-2

I am currently working on adding a gradient background with some transparency to a radar graph within a react component. So far, I have only found solutions that involve referencing a chartjs canvas in an html file, but none for implementing it directly in ...

What is the best way to incorporate a list into a jQuery table?

I am looking to populate a table with a list that is returned from the $.ajax function. Below is a snippet of the code I have been working on. $(document).ready(function() { $.ajax({ type: "POST", url: "Home/LoadTable", success: function(data) ...

Error encountered while executing ExpressJs function that was converted to a promise

Understanding how errors are handled in promises can be a bit tricky, especially for someone new to promises like myself. I'm trying to make the most of them, but I'm not quite there yet. Here is the code snippet I'm working with: app.list ...

Using Vue.js: loading a template within an asynchronous component

Recently delving into Vue.js, I am eager to set up a basic website using it. Each page (About Us, Contact Us, etc) has its corresponding component. Here is my functional starting point Vue.component('about-us', { template: '<div> ...

The issue with IE-9 is that it is mistakenly picking up the placeholder value as

My HTML code looks like this: <input id="SLOCriteriaOtherText" name="SLOCriteriaOtherText" style="width: 100%;" type="text" data-role="autocomplete" placeholder="Enter name for 'other' metric..." class="k-input" autocomplete="off" role="textb ...

Guide for redirecting puppeteers' attention to a new pop-up interface

Currently, I am utilizing Puppeteer to carry out a test on a website. Upon clicking a button, a new popup browser window emerges displaying a report. Inside this new window lies data that I wish to extract. Is there a method for Puppeteer to switch its foc ...