AJAX status updating more than once on ready state

var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
	console.log('state changed',ajax.readyState, ajax.status)

This is generating status change 4 times. Why 4 times?



0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

1 Like

Ok so it doesn’t give final state, but whole causality of event. I know those states BTW.

Event onreadystatechange means: in moment when state changed. If you would to handle AJAX response, you should to check readyState in your event handler…

if (ajax.readyState === 4) {
    // response processing
    if (ajax.status === 200) {
        // handle success
    } else {
        // handle error
1 Like

BTW if you’re only interested in the success state anyway you might just listen to the load event that will only fire once…

1 Like