Not able to understand the onreadystatechange method in javascript

Namaste. Can anyone explain me the line of code containing the onreadystatechange method?

httpRequest = new XMLHttpRequest();
httpRequest.open(“GET”,“https://reqrest.in/api/users/1”);
httpRequest.send();

httpRequest.onreadystatechange = function() {
if(this.readystate == 4 && this.status == 200) {
//write your code here after getting the successful response from the server.
}
};

I want to understand how the onreadystatechange method works exactly.

Hi @mahimagpatil,

Whenever the status of the request changes, xmlhttp.onreadystatechange will get called and code inside the xmlhttp.onreadystatechange will get executed.

You can add some console logs to check the behaviour. Check this link https://www.w3schools.com/js/js_ajax_http_response.asp

Do let me know in case you need any other information.

1 Like