Basic AJAX Request: XMLHttpRequest
There are a number of common front-end tasks that many of us never touched the deep, dirty APIs for because our beloved JavaScript frameworks have provided easier ways to work with them. That's why I wrote How JavaScript Event Delegation Works, Do a Basic HTTP Request with Node.js, and scores of tutorials about other low level API posts. Next up is XMLHttpRequest, the API with which we use to make our AJAX calls!
Retrieving the XHR Object
Unlike most APIs, getting the core component is actually a bit of work since Internet Explorer used to require an ActiveX component to get AJAX to work:
var request; if (window.XMLHttpRequest) { // Mozilla, Safari, ... request = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE try { request = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { try { request = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {} } }
Bleh; the code is ugly but that's what you should expect behind the curtain, right?
Making a Request
Making a request requires two function calls:
request.open('GET', 'https://davidwalsh.name/ajax-endpoint', true); request.send(null);
The open call defines the request type (get
, post
, etc.) and the send method executes the request. Simple enough! Adding custom headers is simple too:
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Request Callbacks
Of course making requests is somewhat useless if you don't handle the result, and there are two ways to set a callback:
// state changes request.onreadystatechange = function() { if(request.readyState === 4) { // done if(request.status === 200) { // complete console.log(request.responseText) } } }; // addEventListener function callbackFn(e) { // Handle each event } request.addEventListener("progress", callbackFn, false); request.addEventListener("load", callbackFn, false); request.addEventListener("error", callbackFn, false); request.addEventListener("abort", callbackFn, false);
Choose whichever method you'd like but the addEventListener
method is probably more elegant.
That's my simple introduction into creating simple AJAX requests with the native XMLHttpRequest API. For further information about common AJAX tests, like sending form data, check out the Mozilla Developer Network!
On IE 7+ you don’t need the ActiveX object anymore. Just use the native
XMLHttpRequest
object. That would simplify your code sample a lot!Nice little article. I personally love jQuery’s handling of AJAX requests.