7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
  1. Code
  2. News

How to Make AJAX Requests With Raw Javascript

Scroll to top
Read Time: 3 mins

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".


Get RequestGet RequestGet Request

Final Script

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

Object PropertiesObject PropertiesObject 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.

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:


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.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.