Multiplexing Requests

Instead of fighting with the connection limit, it may be better to consider sending the requests in batches. Yes, you read that right we are promoting a batch concept here. Take three or four requests, put them into one Ajax request, and send it on its way to the server. This is just the simple idea of multiplexing applied to Ajax. Now, you should doubt this approach as it would seem to be a return to the old style. However, what is being suggested is not waiting around for a batch request, but...

A ClientSide JS Error Reporter

Given the value of reporting user error conditions, we might explore writing an error handler that communicates back to our server using the one-way pattern, showing how many errors users are experiencing client-side. When JavaScript's onerror handler for the Window object gets called, it will create an image request reporting the situation to a serverside program. We present an example JavaScript error reporter as a .js file with name spacing used heavily so it can easily be included in...

Coupled or Decoupled Architecture

Now that we have seen a complete example, we see that the interplay between the client and the server can get a bit involved. Depending on a person's background or philosophical bend, there are two general approaches for attacking the architecture of a more complex full-Ajax style Web application A more client-focused approach with relatively loose coupling A more server-focused approach that tends to be more tightly coupled What we mean here in terms of coupling is how interdependent or...

Request Headers

One thing that was sorely missing from the traditional JavaScript communication methods was the ability to control requests particularly, setting any needed headers. As seen in the previous POST example, XHRs provide a method setRequestHeader to do just that. The basic syntax is like so header-value where header-name is a string for the header to transmit and header-value a string for the corresponding value. Both standard and custom headers can be set with this method. Following HTTP...

Make Requests with Old IfModifiedSince Header

In the library, it is possible to set an option value of preventCache to true, and it will send a request header of If-Modified-Since with a date in the past so that the request will assume that it needs to be refetched. Prevent Caching if set if request.preventCache Wed, 15 Nov 1995 04 58 08 GMT In the case of Firefox, you don't have to worry about the cache busting problem it simply doesn't cache Ajax requests. But when you do know what you are doing with caching, do you no longer have the...

File Uploading with YUI

As alluded to earlier in the section, the YUI Connection Manager can handle file uploads. When using the setForm method, any occurrence of a file upload field using lt input type file gt will trigger the use of the iframe post technique to upload a file as used in the AjaxTCR library and as discussed in Chapter 2. As a reminder, at the time of this writing, XHR objects have no way to handle file uploads without browser modification. The handling of file uploads with YUI is quite easy, though it...

Fighting the Back Button Blues

Consider what the unchanging URL in an Ajax application means to a Web browser. Every URL change is recorded by a browser, and the user is free to move through the history of these changes using their back and forward buttons. Since the URL is no longer being modified, we in effect break the back button for the user. As we saw in the last chapter and show again here in Figure 9-8, the user moves around the Ajaxified application, instinctively hits the back button, and is ejected from the...

Type Conversion

Type conversion is automatically carried out in JavaScript. Table A-6 shows the common conversion rules when data is automatically converted to one type or another. Automatic conversion happens very often when using relational operators discussed later in the section. It is also possible to force type conversion using a variety of built-in methods summarized in Table A-7. Any nonzero number including negative numbers The number as a string, so 40 becomes 40 while -1.13 becomes -1.13 Number...

The User Interface Implications of Ajax

Traditional Web applications are often criticized for being slow and disruptive because of the necessity of the full page redraw. Ajax applications often appear faster because of the reduction in size of data transmission coupled with the limited amount of screen redraw needed. User Action gt Data Update through User Action gt Data Update through An Ajax-style application should be more pleasing to users when properly implemented. However, such applications do have interface considerations and...

Text and Markup Fragments

If you just plan on displaying the returned data in a Web page, it might be easiest to prepare it for display on the server and send down the text or markup fragment to be directly injected into the page in an as-is format. This send-and-use approach is commonly used in Ajax applications and typically relies on the nonstandard but commonly supported innerHTML property. For example in most of the rating examples, you passed back a simple text string in response to the user's vote, as shown by...

YUI Connection Handling Details

The YUI library provides a number of useful methods to handle connections, though clearly, directly manipulating XHRs allows even more flexibility. For example, in the YUI version used for this book 2.3.0 there is no direct way to perform a synchronous request. However, any gaps may be filled by the time you read this, so check the online documentation for the library just to be sure YUI doesn't support something not discussed here. Header control in YUI is performed automatically in the case...

YUI Request Syntax

The first method in the Connection Manager library we use is asyncRequest , which creates an asynchronous request using an XHR object. The following syntax should look familiar, since it simply wraps an XHR URL, callback, postData The properties passed are as follows method A string indicating the type of HTTP method to use for example, GET, POST, HEAD, and so on URL A string containing the URL to invoke including any query string data callback A user-defined object indicating functions and...

Managing MIME Types

It is very important for Ajax applications that any called server-side code correctly set the MIME type of the returned data. You must always remember if the XHR object receives a data stream with a Content-type header not set to text xml, it shouldn't try to parse and populate the responseXML property. If that happens and you go ahead and try to access that property anyway and perform DOM manipulations, you will raise a JavaScript exception. If content is being retrieved that is truly a...

Cross Site Request Forgery

Cross Site Request Forgery CSRF is a somewhat misnamed and apparently innocuous attack. It is related to XSS and generally relies on the hacker to be able to run code of their design in an end user's browser injected either via an XSS vulnerability or being inadvertently run by the user who's been tricked to visit some evil site. Unlike XSS, in a CSRF attack, the target is not the site where the rogue code is hosted, but some other site. Like XSS, CSRF seems a bit abstract, so it is best to...

XHTML and getElementByld

Most JavaScript programmers are comfortable using the getElementById method, so much so that many employ libraries to create a similar function called . The interest in this function is obvious since instead of having to walk a DOM tree, getElementById or any library similar function, gets you directly to the node that you wish to access. However, if you try this method with a tree found in the responseXML property of an XHR object, you will be disappointed to see that getElementById simply...

JavaScript Protection

If JavaScript is the core of Ajax but it is delivered to an untrustworthy client environment, an attempt should be made to shield it from the unscrupulous. However, you will see that, like anything delivered to a client, you ultimately have to submit to the cold fact that the end user has the code and if their desire, patience, and skills are high enough, they can certainly reverse it, steal it, or find any secret contained within. Note Interestingly, because of the admission of the...

Brute Force Solution

If the last few examples have made you cringe in their ugliness, know that you certainly aren't alone. It turns out that there may be a better solution in the use of a brute force tree walking algorithm. Remember that the DOM forms a tree of any returned well-formed markup. It would be easy enough to do some ordered walk of the tree and check each node for an id attribute using the DOM's getAttribute method. function bruteGetElementById id,startNode var allElements for var j 0 j lt...

status and statusText

After the readyState value has indicated that some headers have been received, the next step is to look at the success or failure of the response by looking at the XHR's status and statusText properties. The status property will contain the numeric HTTP status value such as 200, 404, 500, and so on, while the statusText property will contain the corresponding message or reason text like OK, Not Found, Unavailable, No Data, and so on. Very often, the use of these values in Ajax applications is a...

Building a Rating Widget

When the page completes loading, our Ajaxified rating widget is initialized. We adopt a simple convention of namespaces, prefixing our widgets with AjaxTCR.widget, so in this case, we have AjaxTCR.widget.ratingWidget. We will also adopt a convention that all our widgets should be initialized via public method init , so we would invoke AjaxTCR.widget.ratingWidget.init upon page load to bind this widget into our example document. However, to bind the widget safely so that it does not override...

Reserved Words

There are numerous reserved words in JavaScript versions. Generally speaking, reserved words are reserved from use because they already have a defined meaning in some variant of JavaScript or a related technology. Reserved words generally are categorized in three types 3. Words such as object names or related technology keywords Table A-10 lists the words in the first two categories based upon the JavaScript 1.5 specification combined with Microsoft's Jscript documentation. Note Some reserved...

Sequence Explorer 1

Use Request Queue Concurrent Requests l zl Figure 6-11 Response out of order may not make sense The problem here is not necessarily solved by the use of a request queue. As seen in Figure 6-12, when the checkbox 'Use Request Queue' is selected, the responses can still come back out of order unless the number of concurrent requests is forced to be just one, which can potentially severely throttle the overall progress if one of the requests stalls dramatically. Forcing the responses to be in...

readyState Needs Time to Change

One particularly important aspect of asynchronous communication related to the onreadystatechange functionality is the simple fact that in browser-based JavaScript, callback functions cannot be invoked until the script interpreter has a free moment to do so. There is no suspend and resume aspect to JavaScript execution in the typical single-threaded style that is implemented in Web browsers. If you make a request and then enter into heavy calculations or other blocking activity, control will...

Automatic Communication Fallback

The last section might have seemed like a trip down JavaScript communication method memory lane, but there really was an important purpose for it. Our goal was to remind readers that there are many other ways to communicate to the server so we can add an alternative communication mechanism in case the XMLHttpRequest object is for some reason unavailable. To this end, we add to the AjaxTCR library an option fallback. By default it will be true, but you may override it globally with a call to...

CSRF Attacks on JSON JSONP and Script Responses

As you should recall from Chapter 4, JSON JavaScript Object Notation is a compact and easy to use data format growing in popularity with Ajax applications. It also unfortunately can be abused. For example, log in to the AjaxBank example at http ajaxref.com ch7 jsonarray.php and you might retrieve your bank account information using an Ajax request that returns a JSON array payload shown here t gt Chapter 6 Security - JSON and CSRF - Mozilla FirefoH t gt Chapter 6 Security - JSON and CSRF -...

onProgress and Partial Responses

Firefox already implements a few useful event handlers for the XMLHttpRequest object. The most interesting is the onprogress handler, which is similar to readyState with a value of 3 but is different in that it is called every so often and provides useful information on the progress of any transmission. This can be consulted to not only look at the responseText as it is received, but also to get a sense of the current amount of content downloaded versus the total size. The following code...

ToDo List Introduction Delete Confirm and Transition

To move beyond theory into application, we introduce a simple example here to start bringing the ideas together. The example will start to show the ideas of a to-do list application with which users can manage their favorite things to do. Over this chapter and the next, the application will be expanded to support the ability to add, edit, and delete items in the list and will individually apply nearly all the UI techniques presented in the chapter. In the following chapter, we will bring all...

Variables

Variables in JavaScript should be defined using the keyword var and may be defined multiply and assigned upon definition. var favNum 33, favColor, favTech Ajax Given the loose type nature of JavaScript there is no ability or need in JavaScript 1.7 or earlier to indicate the type of a variable. Some developers may name their variables to provide some clue to their expected type, though this does not guarantee the actual value. var strMyName, objDog, numX, boolLikeSushi For better or worse,...

Encoded Text

As the final example of the endless possibilities for data formats in an Ajax application, we present an encoded text format. If you are concerned with a data transmission being immediately understood by visual inspection, you may decide to encode it. There are a number of ways to encode data. Here we apply a simple base64 encoding to the payload that underneath will be the standard x-www-form-urlencoded scheme. var payload encode64 rating escapeValue ratingVal amp comment escapeValue comment...

First Look at YUI Conveniences

To demonstrate some of the elegance of YUI, we used it to rewrite the ever-present ratings demo from Chapter 3 that used the POST method to submit your feelings about Ajax. As previously mentioned, when using the asyncRequest method, you could pass an appropriately encoded message payload assuming there is a function like the encodeValue available using var postData rating encodeValue ratingVal amp comment encodeValue comment URL, callback, postData However, the YUI library provides the same...

JavaScript s Generators and Iterators

JavaScript 1.7 also introduces a variety of interesting features, many of which are adapted from Python features. For example, a generator is a function that does not return a value but instead returns a yield. When you set the function, it does not execute, but instead binds the values and sets up an iterator. You can then iteratively loop through the function and each loop will return the next yield. As you can see from this example, it will hold the state of the function after each call. var...

responseText

The responseText property holds the raw text of a response body, not including any headers. Despite the name suggesting differently, XHRs are actually neutral to data format. Just about anything can be passed back and held in this property plain text, XHTML fragments, comma-separated values, Javascript, or even encoded binary data. The example http ajaxref.com ch3 responsetextmore.html, shown in Figure 3-5, proves this point as it provides a way to receive the same response in a variety of...

Acknowledgments

Phone book sized technical books are about as close as I can come to the effort of birth, being a male. To me it feels similar ten months of effort, lack of sleep, irritability, strange food cravings, and a huge feeling of relief and pride at the end. Yet it simply can't compare, thus my wife Sylvia really deserves any accolade I might receive for bringing our daughter Olivia to the world during the chaos of this massive book project. I promise no more all new books for a while, just revisions...

Twoway Iframes

As seen in the one-way communication patterns discussion, the iframe method is quite flexible since it supports the posting of data, but in the two-way pattern, there are many other benefits. First, note that the iframe is flexible in what it can receive compared to some of the previously discussed methods. Usually it will receive either plain markup XHTML or XML or markup with some script code to run. However, in theory just about anything could be returned. Of course, this may be dependent on...

Oneway Communication

A simple use of remote JavaScript is to spawn a request to the server to indicate that some event has happened, such as an error condition or a particular user activity like clicking a link to visit another site. In these scenarios the request is considered one-way, as it may not be important that a response be returned to the client. As an example of one-way communication, consider a simple rating system. In this scenario you will present the user with a set of choices to indicate their...

The Rise of Ajax

The name Ajax is new, but the ideas behind it are not. The term was first coined by Jesse James Garrett in an article written in February 2005. However, undoubtedly Jesse would be the first to acknowledge that the idea of Ajax goes back much farther than his application of the new moniker. Microsoft first added the XHR ActiveX object to Internet Explorer 5 in 1999 in support of Outlook Web Access. Numerous developers from around the same time used a variety of techniques such as hidden inline...

Oneway frames with Query Strings

There are many other ways to send information to the server besides making image requests. In fact, just about any tag that references an external URL can be used. For example, inline frames, as defined by the lt iframe gt tag, also support a src attribute to load a document. Using this construct it is possible to employ a similar communication technique as was employed with images. Consider adding an invisible inline frame in the page, like this one lt iframe id hiddenIframe Now find this tag...

Contents

1 Introduction to Ajax Ajax Defined Hello Ajax World The Challenges of Running Ajax Examples Locally 11 The Rise of Ajax Implications of Ajax Summary 2 Pre-Ajax JavaScript Communications Techniques One-way Communication One-way Image Object Technique One-way Iframes with Query Strings One-way Script Tags Other Approaches One-way Iframes with Form Posts Cookie-based Transport Two-way Communications Images for Two-way Communications Two-way Script Tag Communication Less Common Two-way Methods...

The Challenges of Running Ajax Examples Locally

Ajax is, at its heart, fundamentally networked use of JavaScript, and because of that you will likely have problems running examples locally from your system. The main issues have to do with the security concerns of a locally saved JavaScript invoking communication. For example, if you simply copy the previous example and run it from your local disk, the code will not work, with Firefox failing behind the scenes, as shown here Internet Explorer will prompt you to allow or deny the script....