onreadystatechange

The onreadystatechange HTML event attribute defines a JavaScript function to run whenever the readyState property of an element changes, commonly used to monitor the progress of an XMLHttpRequest.
This feature is supported in Web Workers but not in Service Workers.

onreadystatechange Event

The onreadystatechange event fires whenever the readyState property of an XMLHttpRequest changes. It is commonly used to track the progress of an HTTP request.

readyState Values:

ValueState Description
0UNSENT - Request created but not opened yet.
1OPENED - open() method has been called.
2HEADERS_RECEIVED - send() has been called, and headers are available.
3LOADING - Response is being downloaded.
4DONE - Request is complete.
Caution: Avoid using this with synchronous requests, and it should not be utilized in native code.

Syntax

Utilize the event name in methods such as addEventListener() or by assigning it to an event handler property.

script.js
addEventListener("readystatechange", (event) => {});
onreadystatechange = (event) => {};

Event Type

A standard Event without any additional properties.

script.js
const xhr = new XMLHttpRequest();
const method = "GET";
const url = "https://institute.qarpeo.com/";

xhr.open(method, url, true);
xhr.onreadystatechange = () => {
  // In local files, status is 0 upon success in Mozilla Firefox
  if (xhr.readyState === XMLHttpRequest.DONE) {
    const status = xhr.status;
    if (status === 0 || (status >= 200 && status < 400)) {
      // The request has been completed successfully
      console.log(xhr.responseText);
    } else {
      // Oh no! There has been an error with the request!
    }
  }
};
xhr.send();

Values

  • <script>
    • Specifies the function to execute when the event is triggered.

Conclusion

The onreadystatechange event executes a JavaScript function when an element's readyState changes. It is frequently used with XMLHttpRequest to track HTTP request progress and helps in monitoring the loading status of resources like images and scripts. Understanding readyState values is crucial for handling request completion and response processing.