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
    5 Ways that CSS and JavaScript Interact That You May Not Know About

    CSS and JavaScript:  the lines seemingly get blurred by each browser release.  They have always done a very different job but in the end they are both front-end technologies so they need do need to work closely.  We have our .js files and our .css, but...

  • By
    Conquering Impostor Syndrome

    Two years ago I documented my struggles with Imposter Syndrome and the response was immense.  I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions.  I've even caught myself reading the post...

Incredible Demos

  • By
    TextboxList for MooTools and jQuery by Guillermo Rauch

    I'll be honest with you: I still haven't figured out if I like my MooTools teammate Guillermo Rauch. He's got a lot stacked up against him. He's from Argentina so I get IM'ed about 10 times a day about how great Lionel...

  • By
    MooTools Documentation Search Favelet

    I'm going to share something with you that will blow your mind: I don't have the MooTools documentation memorized. I just don't. I visit the MooTools docs frequently to figure out the order of parameters of More classes and how best to use...

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!