Video icon 64
Learning to code? Skill up faster with our practical video courses. Start your free trial today.
Advertisement

How to Make AJAX Requests With Raw Javascript

by
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →

Javascript frameworks have turned simple AJAX functions into one-liners. This is quite incredible, considering the fact that it would require more than twenty to accomplish the same thing with raw Javascript. Nevertheless, it's important to learn what's "under the hood".

Screencast

Get Request

Final Script

This is a relatively simple script that will allow you to asynchronously request pages by using a "load(URL, CALLBACK)" function.

// Our simplified "load" function accepts a URL and CALLBACK parameter.
load('test.txt', function(xhr) {
	document.getElementById('container').innerHTML = xhr.responseText;
});

function load(url, callback) {
		var xhr;
		
		if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
		else {
			var versions = ["MSXML2.XmlHttp.5.0", 
			 				"MSXML2.XmlHttp.4.0",
			 			    "MSXML2.XmlHttp.3.0", 
			 			    "MSXML2.XmlHttp.2.0",
			 				"Microsoft.XmlHttp"]

			 for(var i = 0, len = versions.length; i < len; i++) {
			 	try {
			 		xhr = new ActiveXObject(versions[i]);
			 		break;
			 	}
			 	catch(e){}
			 } // end for
		}
		
		xhr.onreadystatechange = ensureReadiness;
		
		function ensureReadiness() {
			if(xhr.readyState < 4) {
				return;
			}
			
			if(xhr.status !== 200) {
				return;
			}

			// all is well	
			if(xhr.readyState === 4) {
				callback(xhr);
			}			
		}
		
		xhr.open('GET', url, true);
		xhr.send('');
	}

// or with jQuery...
$('#container').load('test.txt');
Object Properties

A Few Notes To Consider While Watching

onreadystatechange will fire five times as your specified page is requested.

  • 0: uninitialized
  • 1: loading
  • 2: loaded
  • 3: interactive
  • 4: complete

A value of "4" is what we're searching for. Once it's been reached, we know that we're free to perform an action with the returned data.

XMLHttpRequest and ActiveXObject

Modern browsers utilize the "XMLHttpRequest" object to make asynchronous requests. That means, if you'd like to ignore IE6, you're free to remove the ActiveXObject check - this section.

		if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
		else {
			var versions = ["Microsoft.XmlHttp", 
			 				"MSXML2.XmlHttp",
			 			    "MSXML2.XmlHttp.3.0", 
			 			    "MSXML2.XmlHttp.4.0",
			 			    "MSXML2.XmlHttp.5.0"];
			 
			 for(var i = 0, len = versions.length; i < len; i++) {
			 	try {
			 		xhr = new ActiveXObject(versions[i]);
			 		break;
			 	}
			 	catch(e){}
			 } // end for
		}

Instead, you could just write "var xhr = new XMLHttpRequest();". Be cautious with this method. Once abstracted to its own "load" function, it's easy to keep the IE check as it is.

Get Out of the Global Space

If making multiple requests, you might consider moving your code into its own object. Then, rather than directly calling the "load" function, you use "myObject.load();". A basic guideline to accomplishing this would be:

var ajax = {
   load : function() {
// paste here
   },

   otherMethod : someFunction() {
// paste here
   }
}

ajax.load();

Conclusion

I've no doubt that some of you will leave a comment stating something along the lines of, "Why would I ever do this when it can be done with just one line of jQuery?" The answer is because you need to learn what's under the hood of your car, so to speak. Frameworks like Mootools and jQuery have made Javascript unbelievably accessible to designers. If you fall into this category, I strongly recommend that you pick up a raw Javascript book as well. There's nothing wrong, in my opinion, with learning both simultaneously. Just be sure that you do learn both!


It's similar to working with WordPress if you don't know PHP. Sure, it's possible - but would you really want to?

Hopefully, this should get you up and running! I'd love to hear your thoughts! Have a great weekend. See you on Monday, or on Twitter!

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Advertisement