Basic AJAX Request: XMLHttpRequest

By  on  

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 WorksDo 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!

Recent Features

  • By
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

  • By
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

Incredible Demos

  • By
    Drag & Drop Elements to the Trash with MooTools 1.2

    Everyone loves dragging garbage files from their desktop into their trash can. There's a certain amount of irony in doing something on your computer that you also do in real life. It's also a quick way to get rid of things. That's...

  • By
    Introducing LazyLoad 2.0

    While improvements in browsers means more cool APIs for us to play with, it also means we need to maintain existing code.  With Firefox 4's release came news that my MooTools LazyLoad plugin was not intercepting image loading -- the images were loading regardless of...

Discussion

  1. 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!

  2. Nice little article. I personally love jQuery’s handling of AJAX requests.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!