Join Joe Marini for an in-depth discussion in this video Creating and handling AJAX requests, part of Prototype and script.aculo.us Essential Training.
In this chapter we're going to talk about how Prototype and AJAX work together. And as you'll see, Prototype and AJAX go together really well. They are like two peas in a pod, two objects in a method. You're going to love working with AJAX once you see how easy Prototype makes it. Before we begin, just a quick word about AJAX. It's beyond the scope of this title to go deep into what AJAX is and how it works and how to set up your server and all those things. I'm going to be focusing in this course on how Prototype works with AJAX and what the Prototype classes are.
If you're not familiar with AJAX, lynda.com has a great title called AJAX Essential Training and you should go watch that first if you need to learn about AJAX. Similarly, the server-side technology that I'm using may be different than the one that you're using, and that's okay. You can take the client-side files that I'll be developing and use them with your server back end, whatever it happens to be. So having said that, let's begin. So Prototype, as I said, provides a pretty comprehensive set of classes for working with AJAX and it's divided into four separate classes.
This object is passed to the callback functions that you supply to Prototype. You won't ever need to create one of these yourself. Prototype just handles all of that for you. There is also two utility classes. there is the AJAX.Updater. The AJAX.Updater handles a pretty common scenario in AJAX development. The scenario is you issue an AJAX request to the server and you get some content back and typically you want to take that content and update it into the page somewhere.
You usually have some kind of container, like a div or some other HTML container that you want to put the content into, and the AJAX.Updater class automates that for you. You simply specify the ID of a page element that the content should go into and AJAX.Updater takes care of that for you. And then the other utility class is called the AJAX.PeriodicalUpdater. And this is also a pretty common scenario. It works the same way as the Updater class does, but it does its execution on a periodical time interval.
So it's kind of like a merging between AJAX.Updater and the Prototype PeriodicalExecuter class that we learned about earlier. So for example, you specify a time period and every few seconds or however long the time period is, the AJAX. PeriodicalUpdater class will issue a request to the server, take the results, and put it into a piece of the page that you specify. Let's quickly review the lifecycle of an AJAX Request. The way that you create an AJAX request in Prototype is by using the AJAX.Request class.
And it's pretty simple. You simply give it a URL to the page on the server that you want to handle the request, and then you define some options and a callback function to handle the response. The way the AJAX.Request works is, first the request is created, then the request is initialized. The request is sent off to the server. The received process begins, and this can happen over and over again as packets arrive from the network, and then the receive is complete. And the way that this is represented in code is that there are corresponding callback functions that you can override in the AJAX.Request object to handle each one of these cases.
Now, the on create function, this one right here, is part of the AJAX.Responders class, and that's a very small utility class and I'll cover in a little bit. These four functions, onInitialized, onLoading, onLoaded and onInteractive, are not 100% supported across all browsers, but that's okay because the vast majority of the time you don't use them. What you really care about are the functions down here: onSuccess, onFailure, onXYZ, or onComplete. And these are the functions that handle the AJAX.Response when it comes back, and we'll take a look at those when we see the example.
When you create an AJAX Request, there are some options and callback overrides you can specify. And I'm only going to go through the most important ones. There are more than this. This is not an exhaustive list, but you can look at the documentation on the AJAX site to see what the other ones are. The options you can specify are asynchronous, and that defaults to true. And that determines whether the request is issued asynchronously or synchronously. You should never set this to false. Always leave it to true. Because if you leave it to false, that means that the request will be issued synchronously and the browser will block waiting for the response from the server.
And the UI will freeze up and the user won't be able to do anything. So always use asynchronous. The retrieval method can be either POST or GET. And that corresponds to HTTP POST and GETS. It defaults to POST, but you can also specify GET if you're not sending any parameters to the server. And speaking of parameters, the next option, parameters, lets you specify the parameters for what this request is. And you can pass in either a string or a Prototype hash object or just a plain object and those will be converted for you into parameters that the server can handle.
Then the functions, there is onCreate and that's called when the request is first created and that's part of the AJAX.Responders class, and we'll see how that's a nice little utility in a moment. The onSuccess and onFailure functions are called when the request is complete and they are called separately. The onSuccess function is called when the response code from the server is in the 200 range, meaning that everything went fine. And onFailure is called when an error occurred and the response code is not in the 200s. So you can handle both success and failures in different functions.
So the best practice is not to use onComplete. You should really use onSuccess and onFailure and handle those results individually. And then there is the Response object. The AJAX.Response object is passed to each one of those functions when the response is received from the server. And again, I'm just going to go into the most important ones here. The first three contain the response information from the server based upon what kind of content was passed back. For example, if plain text content was sent back, then the responseText field will have the text content of the server.
So I'm going to switch over to the code. So here I'm in my Editor and this is the AJAX sample that we're going to write. This is going to issue a basic request to the server. So let's take a quick look at the page. What we're going to do is we're just going to do a simple example where we're going to type in the name of a document on the server to retrieve and when I click this button, we're going to get that content and then display it to the user in an alert. And if you look at the example files folder, this is the example files for the AJAX example.
There is a document in here called text.txt and it just contain some sample text. This is the content that's going to come back from the server. So what we need to do is go back to the source. So to create an AJAX request, what we're going to do is when the button for getting the content is clicked, we're just going to call new AJAX.Request, and we need to fill this object out with the parameters that we need to get from the server.
If you look down here in the source code, you'll see that there is an input, right here there is a text field, with an ID of Text1 on it, and that's going to contain the name of the document that we're getting. So we go back up here to the AJAX. Request and what we're going to do is pass the document name to the server and retrieve the content. So to get the value from the field, all we need to do is use the $F() operator, and we'll pass in Text1 as the name of the field that we want to get.
And now we need to pass off some options to the AJAX.Request handler, and those are passed in an object. The first thing we're going to do is set the method to GET, because I'm not passing any parameters here that the server needs to process. I'm just retrieving a document from the server. And then I'm going to define an onSuccess handler. So when the successful request comes back, this function will get called and I'll type a function, and remember the AJAX Response always gets handed to your function, so there is that variable right there.
So what I'm going to do is just simply alert the response.responseText value and that should be the content of the document that we got back. And then I'm going to write onFailure. That's also going to get a function that takes a response object. And in this case, we're going to say, just an alert. "Something bad happened in the AJAX Request," and we'll just alert the response.status.
So that's pretty much all we need to do to issue a successful AJAX request to the server and get content back. So let's go over to the browser and see if this works. So I've already deployed my content up to the server and you can do the same thing using whatever tool you're using to save the file to your server. So what I'm going to do is type in the name of that document that we know is there, and it's called text.txt. So I'm going to click Get the Document, and you can see that the content of that document was successfully returned.
So it says, "This is some sample text in a text document." Let's watch what happens when I type in the name of a document that I know is not there. Let's just call it test.txt. So now when I click the Get Document, you can see that in this case the onFailure method got called and it says, "Something bad happened in the AJAX Request," and the status is 404. And that's the HTTP response code for a file not found. So that's really all there is to it. That's all you need to do to make an AJAX Request call to the server. Just use the AJAX.Request class.
- Retrieving and manipulating web page elements
- Handling web page events and creating custom events
- Traversing the DOM
- Creating and handling AJAX requests
- Using script.aculo.us controls such as Autocompleters, Sliders, and Visual Effects
- Building complex page features like data filtering and image rotators