XMLHttpRequest Details and Making Asynchronous Requests in Ajax

an article added by: Sonja Lande at 06012007


In: Root » » AJAX » XMLHttpRequest Details and Making Asynchronous Requests in Ajax

French Spanish Portuguese Italian German Japanese Chinese Korean Russian Arabic

Regardless of how the XMLHttpRequest type is instantiated, and regardless of the browser or platform, XMLHttpRequest has the same set of methods and properties. Table 4-1 defines the properties and methods. I don’t provide any more details of the methods, as they are used throughout the article. However, I do want to give special attention to the properties, because they are used extensively. When a request has retrieved data, four properties are used to indicate how the request fared. Consider the following HTML code, which references the four properties and is called after the send method has completed:

   document.getElementById( 'httpcode').innerHTML  = xmlhttp.status;
   document.getElementById(  'httpstatus').innerHTML = xmlhttp.statusText;
   document.getElementById( 'result').innerHTML =  xmlhttp.responseText;
 document.getElementById( 'xmlresult').innerHTML  = xmlhttp.responseXML;

The four properties can be subdivided into two subcategories: result and HTTP status. The status and statusText properties retrieve the HTTP result codes. The status property contains an integer value, such as 200 for success. The statusText property contains a textual representation of the HTTP result code, such as OK. The responseText and responseXML properties contain the result of the HTTP request. The difference between the two properties is that responseText contains a string buffer of the results, and responseXML references an XML DOM representation of the results.

Making Asynchronous Requests It is possible to use the XMLHttpRequest object in a synchronous manner, meaning that the moment send is called, the browser stops processing other messages and waits for an answer. But it is a bad idea to use the XMLHttpRequest object in a synchronous manner, as it locks the browser.

For the moment, ignoring the LoadAtomFeed code and focusing on XMLHttpRequest, let’s look at how the browser can be locked. The following example is an ASP.NET page that hangs for ten seconds, and it will be referenced by the XMLHttpRequest object:

   <%@ Page Language = "C#" %>
   <html>
   <head>
   <title>Hanging page</title>
   </head>
   <body>
   <%
   System.Threading.Thread.Sleep( 10000);
   %>
   Hello, after a ten-second sleep!
   </body>
   </html>

The ASP.NET sample is written using the C# programming language, and there is a single statement, System.Threading.Thread.Sleep. The single statement causes the current thread to sleep for ten seconds. The solution is to use an asynchronous Ajax XMLHttpRequest. An asynchronous request will not block the browser, and the user could continue clicking or using other tabs of the browser. The following source code is the properly written Ajax application to use an asynchronous request:

   <html>
   <head>
   <title>Sample Page</title>
   </head>
   <script language="JavaScript"  src="/lib/factory.js"></script>
   <script language="JavaScript"  type="text/javascript">
   var xmlhttp = FactoryXMLHttpRequest();
   function AsyncUpdateEvent() {
   switch( xmlhttp.readyState) {
   case 0:
   document.getElementById( 'status').innerHTML =  "uninitialized";
   break;
   case 1:
   document.getElementById( 'status').innerHTML =  "loading";
   break;
   case 2:
   document.getElementById( 'status').innerHTML =  "loaded";
   break;
   case 3:
   document.getElementById( 'status').innerHTML =  "interactive";
   break;
   case 4:
   document.getElementById( 'status').innerHTML =  "complete";
   document.getElementById( 'result').innerHTML =  xmlhttp.responseText;
   break;
   }
   }
   function GetIt( url) {
   if( xmlhttp) {
   xmlhttp.open( 'GET', url, true);
   xmlhttp.onreadystatechange = AsyncUpdateEvent;
   xmlhttp.send( null);
   }
   }
   </script>
   </head>
   <body>
   <button  onclick="GetIt('/chap02/serverhang.aspx')">Get a  document</button>
   <p><table border="1">
   <tr><td>Document</td><td><span  id="status">No Result</span></td>
   <td><span id="result">No  Result</span></td></tr>
   </table></p>
   </body>
   </html>

There are several new additions to the rewritten Ajax application, and they deal with the technical issues of loading content asynchronously. Let’s start by focusing on the GetIt function. The implementation of GetIt is similar to previous Ajax application examples, except that the third parameter of the open method is true to indicate that the request will be asynchronous. This means that when the send method is called, it will return immediately. Whenever XMLHttpRequest operates in asynchronous modes, feedback is given to the caller on the state of the request. The onreadystatechange property is a function that receives the feedback. It is important to note that the feedback function must be assigned before each send, because upon request completion the onreadystatechange property is reset. This is evident in the Mozilla and Firefox source.

The onreadstatechange property is assigned the AsyncUpdateEvent function. In the implementation of AsyncUpdateEvent is a switch statement that tests the current state of the request. When an asynchronous request is made, the script is free to continue executing other code. This could cause problems if the script attempts to read the request results before the request has been completed. Using the readyState property, it is possible to know the stage of the HTTP request. The readyState property can contain one of five values, where each value represents a request state:

• 0: The XMLHttpRequest instance is in an inconsistent state, and the result data should not be referencing.

• 1: A request is in progress, and the result data should not be retrieved.

• 2: The request has downloaded the result data and is preparing it for reference.

• 3: The script can interact with the XMLHttpRequest instance, even though the data is not completely loaded.

• 4: The request and result data are complete and have been finished.

The request states would seem to indicate that it is possible to manipulate various properties at different states. The problem is that not all browsers support the same property states at the same state codes. The only cross-platform solution is to reference the XMLHttpRequest result properties (status, statusText, responseText, and responseXML) when the request state is equal to 4. When the request state is 4, you can be sure that the result properties contain a valid value.

Executing the asynchronous Ajax application results in a call being made, and the browser is not locked. You can click the button, open a new browser, and surf to another Web site.

legal disclaimer

Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.

related articles

1. Understanding the Definition and Philosophy of Web Services and SOA
Understanding the Definition and Philosophy of Web Services and SOA Wikipedia offers the following definition of Web services:4 The W3C defines aWeb service as a software system designed to support interoperable machine-to-machine interaction over a network. This definition encompasses many different systems, but in common usage the term refers to those services that use SOAPformatted XML envelopes and have their interfaces described by WSDL. For ex...

2. Understanding the Definition and Philosophy of REST
Understanding the Definition and Philosophy of REST REST is a controversial topic among Web service enthusiasts, because it’s considered to stand for the opposite of what Web services and SOA are trying to achieve. The problem with this thinking is that REST is not in contradiction with the abstract definition of SOA and Web services. REST is in contradiction with technologies such as SOAP, WSDL, and WS-* specifications. The following offers a quick definition of REST:...

3. The Easiest Way to Get Started with Ajax and REST
The Easiest Way to Get Started with Ajax and REST Problem You want to know the best way to get started with writing Ajax and REST. Solution When developing an Ajax and REST application, you must decide on the tools and frameworks you’ll use. The choice is simple: Use whatever you’re using today, and write some Ajax applications. You don’t need to change the tools you’re using today. Whether you’re using ASP.NET, JavaServer Pages (JSP), PHP, Ruby, or Python, you...

4. Testing a Dynamic Contract with Ajax
Coding the Contract Using Test-Driven Development Techniques Coding the contract using agile and test-driven development techniques requires writing a number of tests and implementing aMock URL layer. Problem You want to code the contract using these development techniques. Solution To demonstrate, let’s define a use case, implement the use case as a contract, write a test case(s) to implement the contract, implement the contract in the Mock URL, and finally...

5. Testing the Client Side Logic
Problem You want to effectively test your application’s client-side logic. Theory Testing GUI code tends not to be a productive task because of the complications that arise. The main complication is how to test the correctness of a user interface. Imagine a situation where clicking a button causes a table to be filled with data. Now imagine that when a check box is checked and the button is clicked again, a different table is filled with content. The fact that clicking the same button results in two ...

6. Understanding JavaScript and Types
Understanding JavaScript and Types Problem You want to work around the fact that JavaScript does not have types declared for its variables. Theory JavaScript code does not have any variables with a declared type. The lack of typed variables is apparent when you declare functions. That said, not having typed variable declarations does not mean JavaScript has no types or no type safety. Let’s start out with the simple declaration of a function, as illustrated by the following ex...

7. Coding Using Conventions and Not Configurations
Coding Using Conventions and Not Configurations Problem You want to make your JavaScript constructs more efficient by applying the Rails “convention over configuration” principle to them. Theory You may already be familiar with the programming platform Ruby on Rails, which is used to build Web applications. The focus of this recipe is not Ruby on Rails, but one aspect of Ruby on Rails namely, convention over configuration (see http://en.wikipedia.org/wiki/ Ruby_on_Rails for m...

8. Advantage of parameterless functions in JavaScript
Using Parameterless Functions Problem You want to take advantage of parameterless functions in JavaScript. Theory JavaScript functions for the most part have parameters. You may think that the previous sentence states the obvious after all, without parameters, what data could be passed to a function? JavaScript has the ability to declare functions that have no parameters, even though the caller of the function has passed parameters to the function. For example, let’s look at...

9. JavaScripot Functions
Treating Functions Like Objects Problem You want to take advantage of the fact that functions are objects (remember, everything is an object in JavaScript). Theory Many people think that a function is some keyword used in JavaScript. A function is also an object that can be manipulated. Knowing that a function is an object makes it very interesting from the perspective of writing JavaScript code, because the code can treat the function like another other object. This mean...

10. Implementing an Error and Exception Handling Strategy
Implementing an Error and Exception Handling Strategy Problem You want to implement a clean error and exception handling strategy in your applications, to make them run more smoothly. Theory Of course, you might argue that one error is a dialog box and the other is generated in the JavaScript console. The fact that one browser uses a dialog box to show an error and the other does not is a browser issue, not an error issue. A concise way of classifying the two errors is to ...