Working with AJAX
Viewers: in countries Watching now:
- Creating variables, functions, and loops
- Writing conditional code
- Sending messages to the console
- Working with different variable types and objects
- Creating and changing DOM objects
- Event handling
- Working with timers
- Building smarter forms
- Using regular expressions
Working with AJAX
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, mysite.com/somedata.php.
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.
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.