Sunday, January 25, 2009
AJAX Tutorial 2
7:06 PM |
Posted by
Hari Kiran |
Edit Post
First, take this last bit of overview before see into code.
Make sure to clear on this idea of the Web 2.0. When anybody hears the term Web 2.0, one asks; "What's Web 1.0?" Although web 1.0 is rarely heard, it is meant to refer to the traditional Web where we have a very distinct request and response model. For example, go to Amazon.com and click a button or enter a search term. A request is made to a server and then a response comes back to your browser. That request has a lot more than just a list of books and titles, though; it's actually another complete HTML page. As a result, you probably get some flashing or flickering as your Web browser's screen is redrawn with this new HTML page. In fact, you can clearly see the request and response, done by each new page you see.
The Web 2.0 dispenses with this very visible back-and-forth (to a large degree). As an example, visit a site like Gmail or newer Yahoo (links to both of these Web 2.0, Ajax-powered sites are in Resources). On Google Maps, for example, one can drag the map around and zoom in and zoom out with very little redrawing. Of course, requests and responses do go on here, but all behind the scenes. As a user, the experience is much more pleasant and feels a lot like a desktop application. This new feel and paradigm that is observed when someone refers to Web 2.0.
What care should care? how to make these new interactions possible? Obviously, we've still got to make requests and field responses, but it's the redrawing of the HTML for every request/response interaction that gives the perception of a slow, clunky Web interface. So clearly you need an approach that allows you to make requests and receive responses that include only the data you need, rather than an entire HTML page as well. The only time you want to get a whole new HTML page is when ... well ... when you want the user to see a new page.
But most interactions add details or change body text or overlay data on the existing pages. In all of these cases, Ajax and a Web 2.0 approach make it possible to send and receive data without updating an entire HTML page. And to any frequent Web surfer, this ability will makes application feel faster, more responsive, and bring them back over and over again.
Introducing XMLHttpRequest
To make all this flash and wonder actually happen, need to become clear and familiar with a JavaScript object called XMLHttpRequest. This little object; which has actually been around in several browsers for quite a while. This is key to Web 2.0; Ajax, and pretty much everything else you learn about in this column for the next several months. To give a really quick overview, here are just a few of the methods and properties frequently used on this object:
- open(): Sets up a new request to a server.
- send(): Sends a request to a server.
- abort(): Terminates the current request.
- readyState: Provides the current HTML ready state.
- responseText: The text that the server sends back to respond to a request.
Don't worry about understanding all these; each of these methods and properties will be discussed in detail in future. What should be done with this stuff; though, its a good idea of what to do with XMLHttpRequest. Notice that each of these methods and properties relate to sending a request and dealing with a response. In fact, if you saw every method and property of XMLHttpRequest, they would all relate to that very simple request/response model.
So clearly, one won't learn about an amazing new GUI object or some sort of approach to create user interaction; we will work with simple requests and simple responses. It may not sound exciting; but careful usage of this object could change an application interaction method.
The simplicity of new
First, we need to create a new variable and assign it to an instance of the XMLHttpRequest object. That's pretty simple in JavaScript; we just use the new keyword with the object name, like you see in Listing below.
Listing.. Create a new XMLHttpRequest object
<script language="javascript" type="text/javascript">
var request = new XMLHttpRequest();
</script>
So we have created a variable in JavaScript with var, give it a name (like "request"), and then assign it to a new instance of XMLHttpRequest.
At that point, it is ready to be used with above functions.
Error handling
With out error handling in life, several problems could occour. A slightly better approach is to create this object and have it fail if something goes wrong. For example, many older browsers (believe it or not, people are still using old versions of Netscape Navigator) don't support XMLHttpRequest and one need to let those users know that something has gone wrong. Listing below shows how you may create this object so if something fails, it throws out a JavaScript Message (alert).
Listing.. Create XMLHttpRequest with some error-handling abilities
<script language="javascript" type="text/javascript">
var request = false;
try {
request = new XMLHttpRequest();
} catch (failed) {
request = false;
}
if (!request)
alert("Error initializing XMLHttpRequest!");
</script>
Make sure to understand each of these steps:
- Create a new variable called request and assign it a false value. we'll use false as a condition that means the XMLHttpRequest object hasn't been created yet.
- In a try/catch block;
- Try and create the XMLHttpRequest object.
- If that fails catch(failed) block, ensure that request is still set to false.
- Check and see if request is still false (if things are going okay, it won't be).
- If there was a problem (and request is false), use a JavaScript alert to tell users there was a problem.
This is pretty simple; it takes longer to read and write about than it does to actually understand for most JavaScript and Web developers. Now we've got an error-proof piece of code that creates an XMLHttpRequest object and even intimates if something goes wrong.
Dealing with Microsoft Browsers
If same above code is run on Microsoft browser(Internet Explorer), message will be displayed saying "Error initializing XMLHttpRequest!".
Clearly, something isn't working; Internet Explorer is hardly an out-of-date browser and about 70 percent of the world uses Internet Explorer one needs a different approach to deal with Microsoft's browsers.
It turns out that Microsoft supports Ajax, but calls its version of XMLHttpRequest something different.
In fact, it calls it several different things.
For a newer version of Internet Explorer,
Msxml2.XMLHTTP object needs to be used.
Some older versions of Internet Explorer use Microsoft.XMLHTTP; both these objects needs to be supported.
Listing.. Adding support for Microsoft browsers
<script language="javascript" type="text/javascript">
var request = false;
try {
request = new XMLHttpRequest(); //Non Microsoft Browsers. Firefox, Opera, Chrome
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP"); //New Microsoft Browsers
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");//Old Microsoft Browsers
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
</script>
var request = false;
try {
request = new XMLHttpRequest(); //Non Microsoft Browsers. Firefox, Opera, Chrome
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP"); //New Microsoft Browsers
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");//Old Microsoft Browsers
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
</script>
In above code all the required possibilities are checked well. So that if any error occours with creation of XMLHTTP Request, a message will be displayed.
Dynamic Java Script
Take a look back at Listings above and notice that all of this code is nested directly within script tags.
When JavaScript is coded like that and not put within a method or function body, it's called static JavaScript.
This means that the code is run sometime before the page is displayed to the user.
It's not 100 percent clear from the specification precisely when this code runs and browsers do things differently; still, you're guaranteed that the code is run before users can interact with your page. That's usually XMLHttpRequest obejct is now created by Ajax programmers.
With code setup like this, you'll need to call this method before you do any Ajax work. So you might have something like Listing below
Listing.. Use an XMLHttpRequest creation method
<script language="javascript" type="text/javascript">
var request;
/*Function to create XMLHttpRequest Object */
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
/*Calling Function*/
function getInfo() {
createRequest();
// Do something with the request variable
}
</script>
var request;
/*Function to create XMLHttpRequest Object */
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
/*Calling Function*/
function getInfo() {
createRequest();
// Do something with the request variable
}
</script>
The only concern with this code; and the reason most Ajax programmers don't use this approach
is that it delays error notification. Suppose if we have a complex form with 10 or 15 fields, selection boxes, and the like, and some Ajax code is fired when the user enters text in field
14 (way down the form). At that point, getInfo() runs, tries to create an XMLHttpRequest object, and (for this example) fails.
Then an alert is displayed out to the user, telling them (in so many words) that they can't use this application. But the user has already spent time entering data in the form!
That's pretty annoying and annoyance; is not something that typically entices users back to your site.
In the case where static JavaScript is used, the user is going to get an error as soon as they hit your page. Is that also annoying? Perhaps; it could make users mad that your Web application won't run on their browser. However, it's certainly better than displaying out that same error after they've spent 10 minutes entering information. For that reason alone, I encourage to set up code statically and let users know early on about possible problems.
Sending requests with XMLHttpRequest
Once we have our request object, we can begin the request/response cycle. Remember, XMLHttpRequest's only purpose is to allow you to make requests and receive responses. Everything else -- changing the user interface, swapping out images, even interpreting the data that the server sends back -- is the job of JavaScript, CSS, or other code in your pages. With XMLHttpRequest ready for use, now you can make a request to a server.
Welcome to the sandbox
Ajax has a sandbox security model. As a result, your Ajax code (and specifically, the XMLHttpRequest object) can only make requests to the same domain on which it's running. A lot regarding to security will be learnt in future upcoming articles, but for now realize that code running on a local machine can only make requests to server-side scripts on that local machine. If an Ajax code running on www.xyz.com, it must make requests to scripts that run on www.xyz.com.
Setting the server URL
The first thing to be determined is the url of the server to connect. This isn't specific to Ajax -- obviously you should know how to construct a URL by now -- but is still essential to making a connection. In most applications, you'll construct this URL from some set of static data combined with data from the form your users work with. For example, Listing below shows some JavaScript that grabs the value of the phone number field and then constructs a URL using that data.
Listing.. Building a request URL
<script language="javascript" type="text/javascript">
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
function getInfo() {
var phone = document.getElementById("phone").value;
var url = "/lookupCustomer.php?phone=" + escape(phone);
}
</script>
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
function getInfo() {
var phone = document.getElementById("phone").value;
var url = "/lookupCustomer.php?phone=" + escape(phone);
}
</script>
Nothing here should trip up. First, the code creates a new variable named phone and assigns the value of the form field with an ID of phone. Listing below shows the HTML for this particular form in which you can see the phone field and its id attribute.
Listing.. The form
<body>
<p><img src="Site Logo.png" alt="Site Name " /></p>
<form action="POST">
<p>Enter your phone number:
<input type="text" size="14" name="phone" id="phone"
onChange="getInfo();" />
</p>
<p>Your order will be delivered to:</p>
<div id="address"></div>
<p>Type your order in here:</p>
<p><textarea name="order" rows="6" cols="50" id="order"></textarea></p>
<p><input type="submit" value="Order" id="submit" /></p>
</form>
</body>
<p><img src="Site Logo.png" alt="Site Name " /></p>
<form action="POST">
<p>Enter your phone number:
<input type="text" size="14" name="phone" id="phone"
onChange="getInfo();" />
</p>
<p>Your order will be delivered to:</p>
<div id="address"></div>
<p>Type your order in here:</p>
<p><textarea name="order" rows="6" cols="50" id="order"></textarea></p>
<p><input type="submit" value="Order" id="submit" /></p>
</form>
</body>
Also notice when phone number changed or entered, getInfo() method gets fired shown in Listing above. That method then grabs the number and uses it to construct a URL string stored in the 'url' variable. Remember: Since Ajax code is sandboxed and can only connect to the same domain, one need not have a domain name in your URL. In this example, the script name is lookupCustomer.php. Finally, the phone number is appended to this script as a GET parameter: "phone=" + escape(phone).
Here, escape method is to send the clear text correctly. For example, any spaces in the phone number are converted to "%20" characters, making it possible to pass the characters along in the URL.
Similarly according to requirement, any number of parameters can be added to the query string seperating them with " & ".
Opening the request
With a URL to connect to, request could be configured. This will be accomplished using open() method on your XMLHttpRequest object. This method takes as many as five parameters:
- request-type: The type of request to send. Typical values are GET or POST, but you can also send HEAD requests.
- url: The URL to connect.
- asynch: True if you want the request to be asynchronous and false if it should be a synchronous request. This parameter is optional and defaults to true.
- username: If authentication is required, you can specify the username here. This is an optional parameter and has no default value.
- password: If authentication is required, you can specify the password here. This is an optional parameter and has no default value.
Typically, first three will be used. In fact, even when we want to send an asynchronous request, we should specify "true" as the third parameter.
That's the default setting, but it's a nice bit of self-documentation to always indicate if the request is asynchronous or not.
Put it all together; end up with a line that looks a lot like Listing below.
Listing.. Open the request
function getInfo() {
var phone = document.getElementById("phone").value;
var url = "/lookupCustomer.php?phone=" + escape(phone);
request.open("GET", url, true);
}
var phone = document.getElementById("phone").value;
var url = "/lookupCustomer.php?phone=" + escape(phone);
request.open("GET", url, true);
}
Does open() open?
Internet developers disagree about what exactly the open() method does. It does not actually open a request. If we need to monitor the network and data transfer between your XHTML/Ajax page and the script that it connects to, we wouldn't see any traffic when the open() method is called. It's unclear why the name was chosen, but clearly it is not a good choice.
Once the URL figured out, then this is pretty trivial. For most requests, using GET is sufficient (we will see the situations in which we may want to use POST in future articles); that, along with the URL, is all we need to use open().
A teaser on asynchronicity
Later in the series , significant time will be spent on writing and using asynchronous code. But one should have an idea of why that last parameter in open() is so important.
In a normal request/response model; think Web 1.0 here, the client makes a request to the server.
That request is synchronous; in other words, the client waits for a response from the server.
While the client is waiting, we usually get at least one of several forms of notification that you're waiting:
- An hourglass (on Windows).
- A spinning beachball (on Mac machines).
- The application essentially freezes and sometimes the cursor changes.
This is what makes Web applications in particular feel clunky or slow; the lack of real interactivity. When you push a button, your application essentially becomes unusable until the request you just triggered is responded to. If we've made a request that requires extensive server processing, that wait might be significant (at least for today's multi-processor, DSL, no-waiting world).
An asynchronous request though, does not wait for the server to respond.
You send a request and then your application continues on. Users can still enter data in a Web form, click other buttons, even leave the form.
There will be no freeze of application. The server quietly responds to the request and when it's finished, it let's the original requestor know that it's done (it'll be seen in a moment).
The end result is an application that doesn't feel clunky or slow, but instead is responsive, interactive, and makes feel faster.
This is just one component of Web 2.0, but it's a very important one. All the slick GUI components and Web design paradigms can't overcome a slow, synchronous request/response model.
Sending the request
Once we configure the request with open(), we are ready to send the request. Fortunately, the method for sending a request is named more properly than open(); it's simply called send().
send() takes only a single parameter, the content to send. But before you think too much on that, recall that you are already sending data through the URL itself:
var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone);
Although you can send data using send(), we can also send data through the URL itself.
In fact, in GET requests (which will constitute as much as 80 percent of your typical Ajax usage), it's much easier to send data in the URL.
When we start to send secure information or XML, then we need to look at sending content through send(); both secure data and XML messaging could be used in a later article in this series.
When you don't need to pass data along through send(), then just pass null as the argument to this method.
So, to send a request in the example you've seen throughout this article, that's exactly what is needed (see Listing below).
Listing.. Sending the request
function getCustomerInfo() {
var phone = document.getElementById("phone").value;
var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone);
request.open("GET", url, true);
request.send(null);
}
var phone = document.getElementById("phone").value;
var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone);
request.open("GET", url, true);
request.send(null);
}
Specifying a callback method
At this point, we have done very little that feels new, revolutionary, or asynchronous.
Granted, that little keyword "true" in the open() method sets up an asynchronous request. But other than that, this code resembles programming with Java servlets and JSPs, PHP, or Perl. So what's the big secret to Ajax and Web 2.0?
The secret revolves around a simple property of XMLHttpRequest called onreadystatechange.
First, be sure to understand the process that is created in this code (review Listing above if needed). A request is set up and then made.
Additionally, because this is an asynchronous request, the JavaScript method (getInfo() in the example) will not wait for the server. So the code will continue; in this case, that means that the method will exit and control will return to the form.
Users can keep entering information and the application isn't going to wait on the server.
This creates an interesting question, though:
What happens when the server has finished processing the request?
The answer, at least as the code stands right now, is nothing! Obviously, that's not good, so the server needs to have some type of instruction on what to do when it's finished processing the request sent to it by XMLHttpRequest.
Referencing a function inJavaScript. Since JavaScript is a loosely typed language and you can reference just about anything as a variable.
So if you declare a function called updatePage(), JavaScript also treats that function name as a variable. In other words, you can reference the function in your code as a variable named updatePage
This is where that onreadystatechange property comes into play.
This property allows us to specify a callback method. A callback allows the server to (can you guess?) call back into the web page's code. It gives a degree of control to the server, as well; when the server finishes a request, it looks in the XMLHttpRequest object and specifically at the onreadystatechange property.
Whatever method is specified by that property is then invoked. It's a callback because the server initiates calling back into the Web page; regardless of what is going in the Web page itself.
For example, it might call this method while the user is sitting in her chair, not touching the keyboard; however, it might also call the method while the user is typing, moving the mouse, scrolling, clicking a button ... it doesn't matter what the user is doing.
This is actually where the asynchronicity comes into play: The user operates the form on one level while on another level, the server answers a request and then fires off the callback method indicated by the onreadystatechange property. So you need to specify that method in your code as shown in Listing below
Listing.. Set a callback method
function getCustomerInfo() {
var phone = document.getElementById("phone").value;
var url = "/lookupCustomer.php?phone=" + escape(phone);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
var phone = document.getElementById("phone").value;
var url = "/lookupCustomer.php?phone=" + escape(phone);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
Pay close attention to where in the code this property is set; it's before send() is called. You must set this property before the request is sent, so the server can look up the property when it finishes answering a request. All that's left now is to code the updatePage() which is the focus of the last section in this article.
Handling server responses
When a request is made, your user works happily in the web form (while the server handles the request), and now the server finishes up handling the request. The server looks at the onreadystatechange property and figures out what method to call. Once that occurs, one can think of your application as any other app, asynchronous or not.
In other words, we don't have to take any special action writing methods that respond to the server; just change the form, take the user to another URL, or do whatever else to be done in response of the Server.
In this section, we'll focus on responding to the server and then taking a typical action; changing on the fly part of the form the user sees.
Callbacks and Ajax
We've already seen how to let the server know what to do when it's finished:
Set the onreadystatechange property of the XMLHttpRequest object to the name of the function to run.
When the server has processed the request, automatically that function will be called. We don't need to worry about any parameters to that method. we'll start with a simple method like in Listing.
Listing.. Code the callback method
<script language="javascript" type="text/javascript">
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
function getInfo() {
var phone = document.getElementById("phone").value;
var url = "/lookupCustomer.php?phone=" + escape(phone);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
/*This function is called after server has completed its work regarding to response*/
function updatePage() {
alert("Server is done!");
}
<script>
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
function getInfo() {
var phone = document.getElementById("phone").value;
var url = "/lookupCustomer.php?phone=" + escape(phone);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
/*This function is called after server has completed its work regarding to response*/
function updatePage() {
alert("Server is done!");
}
<script>
This just displays a handy alert; to intimate when the server is done. Try this code in your own page, save the page, and then pull it up in a browser (if you want the XHTML from this example, refer back to Listing above). When a phone number and field is left, alert popup should be seen; but click OK and it pops up again ... and again.
Depending on your browser, you'll get two, three, or even four alerts before the form stops popping up alerts. So what's going on? It turns out that you haven't taken into account the HTTP ready state, an important component of the request/response cycle.
HTTP ready states
Earlier, I said that the server, once finished with a request, looks up what method to call in the onreadystatechange property of XMLHttpRequest. That's true, but it's not the whole truth. In fact, it calls that method every time the HTTP ready state changes. So what does that mean? Well, we've got to understand HTTP ready states first.
An HTTP ready state indicates the state or status of a request. It's used to trace if a request has been started, if it's being answered, or if the request/response model has completed. It's also helpful in determining whether it's safe to read whatever response text or data that a server might have supplied. There are 5 Ready states in AJAX Applications:
- 0: The request is uninitialized (before you've called open()).
- 1: The request is set up, but hasn't been sent (before you've called send()).
- 2: The request was sent and is being processed (you can usually get content headers from the response at this point).
- 3: The request is being processed; often some partial data is available from the response, but the server hasn't finished with its response.
- 4: The response is complete; we have server's response and use it.
As with almost all cross-browser issues, these ready states are used somewhat inconsistently. You might expect to always see the ready state move from 0 to 1 to 2 to 3 to 4, but in practice, that's rarely the case. Some browsers never report 0 or 1 and jump straight to 2, then 3, and then 4. Other browsers report all states. Still others will report ready state 1 multiple times. As we saw in the last section, the server called updatePage() several times and each invocation resulted in an alert box popping up; probably which is not intended.
For Ajax programming, the only state you need to deal with directly is readyState 4, indicating that a server's response is complete and it's safe to check the response data and use it. To account for this, the first line in your callback method should be as shown in Listing below.
Listing.. Check the ready state
function updatePage() {
if (request.readyState == 4)
alert("Server is done!");
}
if (request.readyState == 4)
alert("Server is done!");
}
This change checks to ensure that the server really is finished with the process. Try running this version of the Ajax code and you should only get the alert message one time, which is as it should be.
HTTP status codes
Despite the apparent success of the code in Listing above, there's still a problem;
What happens if server finishing processing and reports an error?
Remember, that server-side code should care if it's being called by Ajax, a JSP, a regular HTML form, or any other type of code; it only has the traditional Web-specific methods of reporting information. And in the Web world, HTTP codes can deal with the various things that might happen in a request.
For example, we've certainly entered a request for a URL, typed the URL incorrectly, and received a 404 error code to indicate a page is missing.
This is just one of many status codes that HTTP requests can receive as a status. In each of these cases, these are codes that result from a completed response. In other words, the server fulfilled the request (meaning the HTTP ready state is 4), but is probably not returning the data expected by the client.
In addition to the ready state then, we also need to check the HTTP status. we are looking for a status code of 200 which simply means okay. With a ready state of 4 and a status code of 200, we are ready to process the server's data and that data should be what we've asked for. Add another status check to your callback method as shown in Listing below.
Listing.. Check the HTTP status code
function updatePage() {
if (request.readyState == 4)
if (request.status == 200)
alert("Server is done!");
}
if (request.readyState == 4)
if (request.status == 200)
alert("Server is done!");
}
To add more robust error handling, with minimal complication; we might add a check or two for other status codes; check out the modified version of updatePage() in Listing below.
Listing.. Adding some light error check
function updatePage() {
if (request.readyState == 4)
if (request.status == 200)
alert("Server is done!");
else if (request.status == 404)
alert("Request URL does not exist");
else
alert("Error: status code is " + request.status);
}
if (request.readyState == 4)
if (request.status == 200)
alert("Server is done!");
else if (request.status == 404)
alert("Request URL does not exist");
else
alert("Error: status code is " + request.status);
}
Now change the URL in your getInfo() to a non-existent URL and see what happens. An alert should say URL does not exists; perfect! This's hardly going to handle every error condition, but it's a simple change that covers 80 percent of the problems that can occur in a typical Web application.
Reading the response text
Now that we make sure the request was completely processed (through the ready state) and the server gave you a normal, okay response (through the status code), one can finally deal with the data sent back by the server. This is conveniently stored in the responseText property of the XMLHttpRequest object.
Details about what the text in responseText looks like, in terms of format or length, is left intentionally displayed. This allows the server to set this text to virtually anything. For instance, one script might return comma-separated values, another pipe-separated values (the pipe is the | character), and another may return one long string of text. It's all up to the server.
In the case of the example used in this article, the server returns a customer's last order and then their address, separated by the pipe symbol. The order and address are both then used to set values of elements on the form; Listing below shows the code that updates the display.
Listing.. Dealing with server's response
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText.split("|");
document.getElementById("order").value = response[0];
document.getElementById("address").innerHTML =
response[1].replace(/\n/g, "
");
} else
alert("status is " + request.status);
}
}
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText.split("|");
document.getElementById("order").value = response[0];
document.getElementById("address").innerHTML =
response[1].replace(/\n/g, "
");
} else
alert("status is " + request.status);
}
}
First, the responseText is pulled and split on the pipe symbol using the JavaScript split() method. The resulting array of values is dropped into response. The first value, the customer's last order; is accessed in the array as response[0] and is set as the value of the field with an ID of "order." The second value in the array, at response[1], is the customer's address and it takes a little more processing. Since the lines in the address are separated by normal line separators (the "\n" character), the code needs to replace these with XHTML-style line separators, <br /> s. That's accomplished through the use of the replace() function along with a regular expression. Finally, the modified text is set as the inner HTML of a div in the HTML form. The result is that the form suddenly is updated with the customer's information.
Before this article closed up; another important property of XMLHttpRequest is called responseXML. Guess what that property contains?
An XML response in the event that the server chooses to respond with XML. Dealing with an XML response is quite different than dealing with plain text and involves parsing, the Document Object Model (DOM), and several other considerations.
More will be learnt in future articles regarding to XML and DOM parsing. Still, because responseXML commonly comes up in discussions surrounding responseText, it's worth mentioning here.
For many simple Ajax applications, responseText is all you need, but you'll soon learn about dealing with XML through Ajax applications as well.
Labels:
Ajax
Subscribe to:
Post Comments (Atom)
Blog Archive
-
►
2013
(1)
- ► September 2013 (1)
-
►
2011
(7)
- ► April 2011 (7)
-
►
2010
(1)
- ► April 2010 (1)
-
▼
2009
(11)
- ► December 2009 (2)
- ► February 2009 (3)
-
►
2007
(3)
- ► October 2007 (3)
Categories
- Ajax (6)
- Buddha (2)
- Buddhism (2)
- Favorite Movie (1)
- First (1)
- Four Noble Truths (1)
- Ganesha (1)
- Hindu Deities (2)
- Hinduism (3)
- Krishna (1)
- Meditation (1)
- Namasthe (1)
- PHP Basics (3)
- power ful (1)
- respecting others (1)
- salutation (1)
- siva (1)
- siva tandava stotram (1)
- Speed up windows (1)
- Spiritual (1)
- Start up Programs (1)
- stotram (1)
- Windows Services (1)
- XP optimization (2)
- XP Services (1)
Powered by Blogger.
0 comments:
Post a Comment