New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Working with AJAX

From: JavaScript Essential Training

Video: Working with AJAX

One of the reasons for the resurgence of JavaScript in recent years is the enormous popularity of what's come to be known as AJAX. Now, AJAX sounds like a separate technology or a language; it isn't. It's just a useful buzzword to describe a cool technique we can do with JavaScript. While it officially stands for Asynchronous JavaScript and XML, well, it's really more to do with AJAX being a good acronym than anything else, because it doesn't even require XML. As far as we're concerned, AJAX is JavaScript.

Working with AJAX

One of the reasons for the resurgence of JavaScript in recent years is the enormous popularity of what's come to be known as AJAX. Now, AJAX sounds like a separate technology or a language; it isn't. It's just a useful buzzword to describe a cool technique we can do with JavaScript. While it officially stands for Asynchronous JavaScript and XML, well, it's really more to do with AJAX being a good acronym than anything else, because it doesn't even require XML. As far as we're concerned, AJAX is JavaScript.

It's just a very specific use of it. What it means is that after a web page has opened in the user's browser, we can have JavaScript behind the scenes communicate back to the server, even pass and retrieve data, and update parts of the page without the entire page itself needing to reload. A simple example, if you've used, for example, Google, and started typing, and found it able to start to fill out the information that it thinks you're looking for and actually update the page as you're typing, this is AJAX going on.

As I'm typing, JavaScript is passing these characters to the web server, which is then returning the most likely results as I type and updating the page without me actually refreshing the page at all. If you use an online map, the ability to scroll into places, or to zoom in and as I zoom in start seeing more and more explicit data is the same idea, that this is being fetched from the server as I'm using the Zoom button. Now, in a lot of cases this is almost transparent if I'm working with it slowly, but if I start to drag quite quickly, you'll often see it hurrying up to try and fill in that data for me.

Either way, it's certainly usable. So this technique, this AJAX ability, lets you make more responsive sites, sites that can behave like real applications. And for things like search, autocomplete, and maps, being able to load data on the fly actually makes these sites possible. There is no way we could load all the data upfront. AJAX builds on all these skills we've been working with so far: understanding basic JavaScript, grabbing and manipulating DOM elements. There are two new things we need to be able to do. One is, from JavaScript, create an object that will call the server.

We're creating a request here. And two, then is a very separate part, is let the server pass information to us to deal with any response. Now, these are done as two distinct steps rather than say one function call, because we don't know how long it's going to be between the request and getting the response, and we don't want to hang the page while we wait. This is the asynchronous part of AJAX. So how do we do this? Well, to do it we work with a new object, the XMLHttpRequest object.

This is the middleman between our page loaded in the browser and the server side, any communication we want to do. But unfortunately, it's actually one of those objects with a cross-browser difference, so I can't just write a line of code like this that creates it. I first have to see if it exists. So what I do is something more like this. I'll just define the variable, and then I'm going to do a feature check, ask if certain objects exist on this browser. In this case, what I'm asking is if (window.XMLHttpRequest). That doesn't do anything except ask, is there an object of this name? If there is, I know I'm on Firefox or Safari, or a browser like that, and I can then go ahead and create a new XMLHttpRequest.

If that returns false, I'll then go on and check, well, do you have window.ActiveXObject? If that's true then I'm running on Internet Explorer, and I will create it as the Microsoft.XMLHTTP object done this way. This is one of those areas where you can't really blame Microsoft for being a little different, because they actually did invent this object in the first place. So they're not just trying to do a different version of it; they just have their own specific reasons for creating it. Now, what I have to do after this is I haven't yet said, what am I calling? Where on the server am I reaching to? Have I executed this request or not? So I do need to go ahead and configure and send it, but not yet, because I first have to tell it what to do when a response comes in.

That's the second part of this. Now, that request object, when we execute it, will start to kick off events the same way as a lot of things kick off events. The one we're really interested in will be the onreadystatechange event. And the same way as dealing with say a userClick event or a windowLoad event, we say, okay, when this event is occurring on that request object, I'm going to call, in this case, an anonymous function, which right now will just output a message to console.log.

However, as we'll see, this event is actually quite chatty, and the request will cause this event to be called multiple times before we're completely finished with the entire communication request. I'll get into that in just a moment. But after I've been prepared to accept this response, after I've created this event handler, then I can configure and send it. I tell it where the request is going. In this case, I say I am using a GET rather than a POST. I am going to call the address, in this case,

The last argument here of true means yes, this is asynchronous, so as soon as we do it, we're going to go ahead and execute any other JavaScript code, and we're just going to allow the browser itself to handle any response-- we're not going to wait for it. And then we send it. I am passing Null here, but if I had some parameters to send, I could do that too. So let's see a simple example in code. I have about as straightforward an HTML page as I can have here. I've got one div called mainContent with "This is an AJAX Example," and in my script file that I'm linking to, I have some simple boilerplate code for creating this AJAX request.

So on Line 4, I defined a variable called myRequest. On Line 7 I am going to ask, if the XMLHttpRequest object exists. If so, we're in Firefox or Safari, I'll go ahead and create it. If not, we're probably in IE, so I'll go ahead and create it the different way. Either way, by the time I get to Line 14, I should have an object. I am going to create an event handler for our request, which in this case we'll just call console.log, and say, "We were called!" Line 19, now I have to configure that request. Where is it going? In this case I am going to say to a GET, and I've just given it the address of simple.txt, which is effectively going to treat it as a relative link here.

I wanted to do it simply so that I didn't have to work with creating up server- side scripts, all that kind of thing. I do have a file that's existing at the same location as my HTML page and my JavaScript file. It's just called simple.txt and it says, "This is the contents of a simple text file." So that's what we're after. And then we're going to send the request. Now, after I execute this code if I did have more JavaScript code, it would just go on and execute any subsequent JavaScript.

We're not waiting for the request to come back. That's why we set up the event handler. Because whether that request takes 10 milliseconds or 10 seconds, we don't want to block, meaning we don't want to hang the page. So we just go ahead, and when it calls this back, it will jump back here into this anonymous function. So let's see if this works. I'm going to jump over and just execute this code, open it up in Firefox. Now, I do have my console open here, and I can actually say that I got that console.log message that we were called five times, which is a little strange.

Well no, it's not, really. The thing is is that this onreadystatechange event actually gets called multiple times, and every time it's called it's at a different stage of the request and response, and it passes in a little piece of information. I am going to write that out, so you see what it looks like. I am going to say console.log. I have a property of the request object called readyState. So if I save this, go back over and refresh it again, I can see that I get called several times with a different state: 1, 2, 3, and 4; in fact, 4 is the one that I am interested in.

When there is a ready state of 4, I then know that I've gotten a response back from the server from whatever I was asking for. So what I am going to do is just put in a little bit of code here. I am going to be starting off with an if statement. If (myRequest.readyState === 4) meaning I know I've got a response back, then I am just going to call a few DOM methods here. First, I am going to create a new paragraph element and call it p. Then I am going to create a new TextNode.

Now, here's the only important bit about this. We've seen everything except this. Once that response has been received, I will have a property of the request object called responseText, and that's going to be whatever I got back from that call. So we create the element. We create a TextNode with that content in it. I then add the TextNode to the paragraph. I then add the paragraph to the DOM tree, to the mainContent div. So save this file, jump back over into the browser, and what I am hoping for is when I refresh this I will see the page itself updating that content. There we go! This is the contents of a simple text file.

Now, obviously because all my files are running locally, what I am not seeing is perhaps the slight delay that I might have in updating this page, but this is still proving the point. Yes, it's a simple example here, but the entire process of doing this in a production site is the same. We're creating a request, we're setting up a handler to wait for any response, and then we're firing the request off. Now, as with other areas where there are cross-browser differences, when I am doing anything substantial with AJAX, I am a fan of using a library like jQuery which provides helper functions, so you don't have to worry about writing the cross-browser check, because it can get a little more complex with older browsers, for example.

So take a look at that if that's an area that you're interested in.

Show transcript

This video is part of

Image for JavaScript Essential Training
JavaScript Essential Training

56 video lessons · 99471 viewers

Simon Allardice

Expand all | Collapse all
  1. 3m 28s
    1. Welcome
      1m 1s
    2. What you should know
      1m 44s
    3. Using the exercise files
  2. 15m 41s
    1. Introduction to JavaScript
      8m 6s
    2. Creating your first JavaScript
      2m 13s
    3. Getting to know the tools and applications
      5m 22s
  3. 56m 8s
    1. Understanding the structure of JavaScript code
      7m 9s
    2. Where to write your JavaScript
      3m 56s
    3. Creating variables
      6m 21s
    4. Working with conditional code
      5m 44s
    5. Working with operators
      13m 28s
    6. Sending messages to the console
      2m 59s
    7. Working with loops
      8m 1s
    8. Creating functions
      8m 30s
  4. 36m 13s
    1. Working with arrays
      7m 57s
    2. Working with numbers
      6m 13s
    3. Working with strings
      8m 27s
    4. Working with dates
      5m 38s
    5. Working with objects
      7m 58s
  5. 9m 6s
    1. What is the DOM?
      5m 49s
    2. Working with nodes and elements
      3m 17s
  6. 25m 17s
    1. Accessing DOM elements
      11m 3s
    2. Changing DOM elements
      5m 42s
    3. Creating DOM elements
      8m 32s
  7. 24m 45s
    1. Introduction to JavaScript event handling
      8m 16s
    2. Working with onClick and onLoad events
      7m 36s
    3. Working with onBlur and onFocus events
      2m 36s
    4. Working with timers
      6m 17s
  8. 21m 41s
    1. Common JavaScript errors
      7m 14s
    2. Using Firebug
      4m 7s
    3. Going through a debugging session
      10m 20s
  9. 10m 13s
    1. Accessing form elements
      4m 20s
    2. Preventing a form from being submitted
      2m 36s
    3. Hiding and showing form sections
      3m 17s
  10. 9m 49s
    1. CSS and JavaScript
      3m 46s
    2. Removing and applying CSS classes
      2m 16s
    3. Changing inline styles
      3m 47s
  11. 19m 44s
    1. Understanding JavaScript style
      7m 39s
    2. Minifying your code
      4m 28s
    3. Using JavaScript code checkers
      7m 37s
  12. 22m 24s
    1. Introduction to JavaScript libraries
      3m 17s
    2. Linking to multiple JavaScript files
      2m 11s
    3. Introduction to jQuery
      12m 7s
    4. Using a content distribution network to deliver JavaScript files
      4m 49s
  13. 17m 35s
    1. JavaScript in HTML5
      9m 37s
    2. Using Modernizr
      3m 2s
    3. Using Strict Mode
      4m 56s
  14. 33m 3s
    1. Knowing the JavaScript to avoid
      6m 35s
    2. Introduction to regular expressions
      6m 56s
    3. Working with AJAX
      10m 44s
    4. Working with objects and prototypes
      8m 48s
  15. 21m 10s
    1. Example: Countdown
      8m 3s
    2. Example: Resize
      5m 47s
    3. Example: Accordion
      7m 20s
  16. 4m 58s
    1. Where to go from here
      4m 0s
    2. Goodbye

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes changes my life forever. @JosefShutter
@lynda is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold

Are you sure you want to delete this note?


Thanks for signing up.

We’ll send you a confirmation email shortly.

Sign up and receive emails about and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from

Sign up and receive emails about and our online training library:

Here’s our privacy policy with more details about how we handle your information.

submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.