AJAX status updating more than once on ready state

var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
	console.log('state changed',ajax.readyState, ajax.status)
}
console.log(ajax);
ajax.open('GET','https://randomuser.me/api/?format=json',true);
ajax.send('');

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

readyState

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

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.