TIL how to initiate a request using native browser
XMLHttpRequest objects, instead of a request library that wraps these objects.
I’ve always used libraries like
jQuery.ajax() to make AJAX requests from my front end applications. Since these libraries just wrap XMLHttpRequest objects, I figured it would be a good exercise to figure out how these requests are made.
Takeaways from this exercise:
Internet Explorer has its own version of XMLHttpRequest called
ActiveXObject. If you want your requests to work in IE, it is necessary to first test to see if ActiveXObject is attached to window, then use that to construct your xhr object instead of
5 states of an XMLHttpRequest: 0) Client Created, request has not been made 1) xhr.open() has been called 2) xhr.sent() has been called, and headers are available from the response 3) xhr.responseText is downloading 4) Request is complete!
You need to attach an
onreadystatechangelistener to your xhr object, which will be called every time the readystate changes. Once
readystate === 4, the responseText has finished downloading and you can begin to parse the response.
You may also attach an
onloadlistener, which will only be fired if the request is successful. If you use this, you should also use an
onerrorlistener, which will fire if the request was unsuccessful and will allow you to handle this gracefully.