onreadystatechange
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:
Value | State Description |
---|---|
0 | UNSENT - Request created but not opened yet. |
1 | OPENED - open() method has been called. |
2 | HEADERS_RECEIVED - send() has been called, and headers are available. |
3 | LOADING - Response is being downloaded. |
4 | DONE - Request is complete. |
Syntax
Utilize the event name in methods such as addEventListener()
or by assigning it to an event handler property.
addEventListener("readystatechange", (event) => {});
onreadystatechange = (event) => {};
Event Type
A standard Event without any additional properties.
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.
onpaste
The onpaste event in HTML is triggered when content is pasted into an element, enabling developers to manage or validate the pasted information.
onvisibilitychange
The onvisibilitychange event attribute defines a JavaScript function to run when the visibility state of a document changes, showing whether the page is in the foreground or background.