Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

The onreadystatechange Property

The readyState property indicates the status of the XMLHttpRequest.

The onreadystatechange property sets a callback function to be executed when the readyState changes.

The status and statusText properties hold the current status of the XMLHttpRequest object.

Property

Description

onreadystatechange

Specifies a function to be executed whenever the readyState property changes.

readyState

Stores the status of the XMLHttpRequest:

  • 0: Request not initialized
  • 1: Server connection established
  • 2: Request received
  • 3: Processing request
  • 4: Request completed, and response is ready

status

  • 200: “OK”
  • 403: “Forbidden”
  • 404: “Page not found”

For a full list, refer to the HTTP Status Messages Reference.

statusText

Returns the status text (e.g., “OK” or “Not Found”).

The onreadystatechange function is triggered whenever the readyState changes.

When the readyState is 4 and the status is 200, the response is ready.

Example

function loadDoc() {
  const xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById(“demo”).innerHTML =
      this.responseText;
    }
  };
  xhttp.open(“GET”“ajax_info.txt”);
  xhttp.send();
}
The onreadystatechange event is triggered four times (1 through 4), once for each change in the readyState.