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

Incredible Demos

  • By
    LightFace:  Facebook Lightbox for MooTools

    One of the web components I've always loved has been Facebook's modal dialog.  This "lightbox" isn't like others:  no dark overlay, no obnoxious animating to size, and it doesn't try to do "too much."  With Facebook's dialog in mind, I've created LightFace:  a Facebook lightbox...

  • By
    :valid, :invalid, and :required CSS Pseudo Classes

    Let's be honest, form validation with JavaScript can be a real bitch.  On a real basic level, however, it's not that bad.  HTML5 has jumped in to some extent, providing a few attributes to allow us to mark fields as required or only valid if matching...

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!