The XMLHttpRequest.readyState property returns the state an XMLHttpRequest client is in. An XHR client exists in one of the following states: Value. State. Description.
To add to the information from Jason - a readyState of 4 means that the program has "heard" back from the server. You want to wait for this (hence the if statement) before executing anything further. Full documention from MDN: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest.
readyState: 4: request finished and response is ready status: 200: "OK" When readyState is 4 and status is 200, the response is ready: since when xmlhttp. readyState == 4 , response is ready, why do we still need xmlhttp.
An Ajax http request has 5 states as your reference documents:
0 UNSENT open() has not been called yet.
1 OPENED send() has been called.
2 HEADERS_RECEIVED send() has been called, and headers and status are available.
3 LOADING Downloading; responseText holds partial data.
4 DONE The operation is complete.
State 4 means that the request had been sent, the server had finished returning the response and the browser had finished downloading the response content. So, it is right to say that the AJAX call has completed.
Yes, it is correct.xhr.readstate===4
means request finished and response is ready. You can refer this for details.
Here is small example:
xmlhttp.open("GET", "test.txt", true);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send(null);
The above script makes a GET request for the relative url "text.txt" (relative to the calling page) It provides the function, which checks the readyState property each time it's called and when it has the value 4 - meaning the load is complete, it displays the responseText to the user with an alert.
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With