Chapter 17

Cleaning Up the Web with AJAX

In This Chapter

arrow Understanding how AJAX can benefit your applications

arrow Using JavaScript alone to create an AJAX application

arrow Using jQuery with AJAX

Chapter 16 introduces you to XML, which is essentially a means of storing textual data in a structured way so that it retains its original context but is easily used by any platform. In that chapter, you see a basic example of what amounts to a database. This chapter looks at XML from a new perspective — as a means of exchanging data with a server and of updating parts of a Web page without reloading an entire page. This technology is called Asynchronous JavaScript and XML (AJAX). It isn’t a new language but merely a new way to use existing standards to perform specialized tasks.

This chapter provides a simple overview of AJAX. You’ve probably seen AJAX at work in the past. This programming technique is used to create some of the effects used by Google Maps, Gmail, YouTube, and Facebook (amongst many others). When you complete this chapter, you’ll know more about AJAX and how it can help you create applications that are more flexible and dynamic.

Introducing AJAX

Many developers have heard of AJAX, assumed it was a special sort of language, and never went any further. AJAX isn’t a new language; it’s a reuse of existing technology to create a new way of dealing with updates to documents. You already know the technologies behind AJAX; all you need to do is apply them in a new way to gain some major advantages in presenting content online. The following sections describe AJAX and present some simple scenarios for using it to create dynamic pages on your site.

Learning the benefits of AJAX

AJAX makes it possible to create dynamic applications that load and run faster and also use fewer network and server resources. The goal of AJAX is to allow changes to a page without having to reload the entire page. Using AJAX makes it possible to create applications that are quite fast without loading the server down with large requests. All the server has to do is send a small piece of data to the caller when requested. This small piece of data travels faster over the network, which means that request latency is also smaller.

remember.eps One of the bigger reasons to use AJAX is that it’s standards-based (created and administered by a standards group). There isn’t some large company out there that controls AJAX. Because it’s standards-based, AJAX runs on any newer browser and platform combination that supports the standards it uses. AJAX relies on these standards:

check.png JavaScript: You use JavaScript to write the code required to handle events at the browser, make requests to the server, and update areas on the page as needed.

check.png Document Object Model (DOM): JavaScript makes use of the DOM to gain access to specific locations on the page.

check.png Cascading Style Sheets (CSS): Using CSS makes it possible to create special effects during data updates. In addition, CSS makes the new data fit in with the existing page content.

check.png eXtensible Markup Language (XML): Any update is going to require some sort of data. XML is a perfect choice because it works anywhere.

check.png XMLHttpRequest object: Communication with the server requires a connection, and the XMLHttpRequest object creates this connection. Chapter 16 shows how to use a synchronous connection to insert XML data onto a page during the loading process. AJAX performs its tasks asynchronously.

Understanding how AJAX works

AJAX doesn’t perform magic. There’s nothing behind the scenes that doesn’t make sense once you understand it. In fact, AJAX performs its task by using a process that’s similar to the one you’ve used for many of the examples in this book. The only difference is that AJAX performs the task over a network wire rather than locally in the same page or an external page in the same folder. Here’s the sequence of events that occur when using AJAX.

1. An event occurs at the browser. (The nature of the event is irrelevant but generally involves a data request of some sort.)

2. JavaScript creates a new XMLHttpRequest object. In this case, the object will be configured to perform its work asynchronously using a callback function.

3. JavaScript sends the request to the server for processing. At this point, the page continues performing tasks as it normally does while waiting for a response.

4. The server receives the XMLHttpRequest object that JavaScript sent and processes it.

5. The server creates a response and sends it back to the browser.

6. The browser’s callback function provided with the original request receives the response from the server.

7. The callback function performs any required post-processing of the response.

8. An update of the information onscreen occurs, and the user sees the result.

Deciphering the XMLHttpRequest object

It may at first seem that XMLHttpRequest object is intensely complicated, but it really isn't if you take it apart and view it a bit at a time. In reality, most developers use only a few well-known methods and properties. However, it's entirely possible that developers would use more features of this object if they knew they existed. The following sections break the XMLHttpRequest object into two pieces: request and response. You use methods and properties to perform these two tasks, so it makes sense to review them from that perspective.

Working with the request

To obtain resources from the server, you must make a request. After all, the server doesn't read minds. You build up a request by using methods and properties, and then you use the send() method to transmit the request you've built. The following list describes the properties normally associated with requests:

check.png timeout: Determines the time, in milliseconds, that the request will continue attempting to obtain a required resource from the server.

check.png withCredentials: Specifies that the request should include the user's credentials when set to true. The credentials allow access to secure resources on the server.

check.png upload: Provides the server with a XMLHttpRequestUpload object that contains data the server requires to fulfill a request.

Now that you have a better idea of which properties are available to make a request, it’s time to look at the methods. The following methods are usually associated with making a request of some type:

check.png open(): Creates a new request. The request can include a number of arguments as defined in the following list in the order you provide them:

method: Determines the method used to access the resource. The two valid choices are GET and POST.

URL: Specifies the location of the resource on the server.

asynchronous: Determines whether the request is made in a synchronous or asynchronous manner. The caller must provide a callback function when this flag is set to true (for an asynchronous request).

username: Contains the user's logon name for secure resource access.

password: Contains the user's password for secure resource access.

check.png setRequestHeader(): Creates a name/value pair to include with the request header. You supply the name and value as two separate arguments that the call uses to create the request header entry.

check.png send(): Transmits the request to the server. It sounds simple, but a number of features are in place to make the process more reliable than simply throwing a request out and hoping something happens. You can read about the entire process if you want at http://www.w3.org/TR/XMLHttpRequest/#infrastructure-for-the-send()-method. However, from a developer's perspective, how send() works isn't nearly as important as what send() returns. The send() method either returns data or an error. Here are the four most common errors you receive and why they happen:

network: Something has happened to stop the request from reaching the server. In some cases, a Domain Name System (DNS) error causes the request to get lost before it reaches the server. In other cases, a Transport Layer Security (TLS) error occurs, which means that your application may not have the required credentials. In fact, network errors can come from a number of sources, but these are the two most common reasons.

abort: The end user has cancelled the request. To cause this error, your application must call the abort() method.

timeout: A request has wandered about looking for the resource it needs and finally given up. Requests have a timeout value associated with them. Otherwise, the request could continue looking for a resource indefinitely if that resource doesn't exist.

request: There's a problem with the request. You normally have to dig deeper to find out precisely what the problem is. However, there are a number of common causes, including: requesting a non-existent resource, not providing a required argument, and providing information of the wrong type.

check.png abort(): Stops execution of the current request.

Working with the response

The XMLHttpRequest object also provides a number of response properties and methods that you use to determine the success or failure of a request. Here are the properties that you commonly use when working with this object:

check.png status: Returns the HTTP status code. A status code of 200 means that the request completed successfully. Any other code normally reflects some sort of problem with the request process. You can find a list of status codes at http://www.w3.org/Protocols/HTTP/HTRESP.html.

check.png statusText: Returns the HTTP status as a textual value. For example, a status code of 200 returns a text value of OK. You can find a list of status text values and their associated codes at http://www.w3.org/Protocols/HTTP/HTRESP.html.

check.png readyState: Specifies the current state of asynchronous processing. The state can be any of these values:

0: Request not initialized

1: Server connection established

2: Request received

3: Processing request

4: Request finished and response is ready

check.png responseType: Returns the value of the Content-Type response header. An application can use this value to determine how to react to the type of response the server has sent. The common return types are

"": An empty string indicates that the return type is unknown or that an error has occurred and there's no response to process.

arraybuffer: The data is in the form of an array.

blob: The sender has used a Binary Large Object (BLOB) to store the data.

document: The data appears as structured information in an XML document. Normally, the document is complete, rather than an XML fragment.

json: The sender has used JavaScript Object Notation (JSON) to encapsulate the data.

text: The information appears as plain text, which may mean that it lacks context and structure. However, some text formats are structured, such as Comma Separated Variable (CSV).

check.png response: Contains the entire response without any interpretation as an object.

check.png responseText: Contains only the text of a response when the responseType value is "" (the empty string) or text. This property returns nothing for other responseType values.

check.png responseXML: Contains only the XML document when the responseType value is "" (the empty string) or document. This property returns nothing for other responseType values.

The response methods help you interact with the response data in some way. Here are the response methods:

check.png getResponseHeader(): Obtains a specific response header value from the response object. You supply the value of the response header you want, such as Content-Type, as an argument to the method. There are no required response headers, and a server can create custom headers, but you can find a list of common response headers at http://www.httpwatch.com/httpgallery/headers.

check.png getAllResponseHeaders(): Creates an array of all of the response headers except those that are listed as Set-Cookie or Set-Cookie2.

check.png overrideMimeType(): Specifies the value of the Content-Type response header.

Performing AJAX Tasks Using JavaScript

Using AJAX with pure JavaScript is a two-part process. First, you must send the request. Second, you must process the response. The following code shows the two parts of the process used to change just part of a page. You must execute this code on your server — it won't respond properly from the local drive. (You can find complete code for this example in the Chapter 17 folder of the downloadable code as AJAX_JavaScript.HTML.)

// Create a connection to the server.

var Connect = new XMLHttpRequest();

nbps;

function LoadDoc()

{

   // Specify which function to use on return.

   Connect.onreadystatechange = ProcessData;

   

   // Make the request.

   Connect.open("GET","Special.txt",true);

   Connect.send();

}

nbps;

function ProcessData()

{

   // Verify the return status.

   if ((Connect.readyState == 4) &&

       (Connect.status == 200))

   {

      // Modify the <div> content.

      document.getElementById("ChangeText").innerHTML =

         Connect.responseText;

   }

}

The code begins by creating an XMLHttpRequest object, Connect, which is used to handle the connection with the server. This object is common to both requesting the data and processing it later.

When a user clicks Change the Text, the button calls LoadDoc(). The first step is to tell Connect where to find the function, ProcessData(), used to process the data later. The code then creates a request for Special.txt using the GET method. Notice that the open() function is set to use an asynchronous call rather than a synchronous call, which you might use when working with XML data.

The ProcessData() function receives input any time that the readyState changes for the connection. However, you don't need to process every change. The code begins by checking for a readyState of 4 and a status of 200, which means that the response has been successfully processed and is ready to use. When this combination occurs, the code changes just the text of the target <div> onscreen.

Making AJAX Easier with jQuery

The example found in the Checking browser and version section of Chapter 2 introduces you to a valuable online library called jQuery. Using jQuery greatly reduces the amount of code you need to write to make AJAX work. In fact, creating an AJAX application becomes relatively simple. Of course, using jQuery always begins with defining the library source, as shown here. (You can find complete code for this example in the Chapter 17 folder of the downloadable code as AJAX_jQuery.HTML.)

<script

   src="http://code.jquery.com/jquery-latest.js">

</script>

Using the latest jQuery version is always a good idea, but you can also download a local copy of jQuery to speed queries from http://code.jquery.com. This example relies on a simple button to execute the event handler shown here:

function ChangeText()

{

   $("#ChangeText").load("Special.txt");

}

The jQuery calls are preceded by a dollar sign ($). This call accesses a <div> with an id of ChangeText. It calls the load() function for that <div> with a resource of Special.txt. When you run the query, you see that the text in the <div> changes without loading the rest of the page.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.119.114