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
    Create a CSS Cube

    CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals.  Add animation and you've got something really neat.  Unfortunately each CSS cube tutorial I've read is a bit...

  • By
    Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

Incredible Demos

  • By
    jQuery Link Nudge Plugin

    A while back I debuted a tasteful mouseover/mouseout technique called link nudging. It started with a MooTools version and shortly thereafter a jQuery version. Just recently Drew Douglass premiered a jQuery plugin that aimed at producing the same type of effect.

  • By
    CSS :target

    One interesting CSS pseudo selector is :target.  The target pseudo selector provides styling capabilities for an element whose ID matches the window location's hash.  Let's have a quick look at how the CSS target pseudo selector works! The HTML Assume there are any number of HTML elements with...

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!