What You’ll Learn in This Chapter:
Common Ajax Errors
The Back Button
Bookmarking and Links
Telling the User That Something Is Happening
Making Ajax Degrade Elegantly
Dealing with Search Engine Spiders
Pointing Out Active Page Elements
Don’t Use Ajax Where It’s Inappropriate
Security
Test Code Across Multiple Platforms
Ajax Won’t Cure a Bad Design
Some Programming Gotchas
In this chapter you’ll learn about some of the common Ajax mistakes and how to avoid them.
Ajax has some common pitfalls waiting to catch the unwary developer. In this chapter, the last chapter of Part V, we’ll review some of these pitfalls and discuss possible approaches to finding solutions.
The list is not exhaustive, and the solutions offered are not necessarily appropriate for every occasion. They should, however, provide some food for thought.
All browsers in common use have a Back button on the navigation bar. The browser maintains a list of recently visited pages in memory and allows you to step back through these to revisit pages you have recently seen.
Users have become used to the Back button as a standard part of the surfing experience, just as they have with the other facets of the page-based web paradigm.
JavaScript has its own equivalent of the Back button written into the language. The statements |
onClick = “history.back()” |
and |
onClick = “history.go(-1)” |
both mimic the action of clicking the Back button once. |
Ajax, as you have learned, does much to shake off the idea of web-based information being delivered in separate, page-sized chunks; with an Ajax application, you may be able to change page content over and over again without any thought of reloading the browser display with a whole new page.
What then of the Back button?
This issue has caused considerable debate among developers recently. There seem to be two main schools of thought:
Create a means of recording state programmatically, and use that to re-create a previous state when the Back button is pressed.
Persuade users that the Back button is no longer necessary.
Artificially re-creating former states is indeed possible but adds a great deal of complexity to Ajax code and is therefore somewhat the province of the braver programmer!
Although the latter option sounds a bit like it’s trying to avoid the issue, it does perhaps have some merit. If you use Ajax to re-create desktop-like user interfaces, it’s worthy of note that desktop applications generally don’t have—or need—a Back button because the notion of separate “pages” never enters the user’s head!
This problem is not unrelated to the Back button issue.
When you bookmark a page, you are attempting to save a shortcut to some content. In the page-based metaphor, this is not unreasonable; although pages can have some degree of dynamic content, being able subsequently to find the page itself usually gets us close enough to seeing what we saw on our previous visit.
Ajax, however, can use the same page address for a whole application, with large quantities of dynamic content being returned from the server in accordance with a user’s actions.
What happens when you want to bookmark a particular screen of information and/or pass that link to a friend or colleague? Merely using the URL of the current page is unlikely to produce the results you require.
Although it may be difficult to totally eradicate this problem, it may be possible to alleviate it somewhat by providing permanent links to specially chosen states of an application.
This is another issue somewhat related to the change of interface style away from separate pages.
The user who is already familiar with browsing web pages may have become accustomed to program activity coinciding with the loading of a new or revised page.
Many Ajax applications therefore provide some consistent visual clue that activity is happening; perhaps a stationary graphic image might be replaced by an animated version, the cursor style might change, or a pop-up message appear. Some of these techniques have been mentioned in some of the chapters in this book.
The chapters in this book have covered the development of Ajax applications using various modern browsers. It is still possible, though, that a user might surprise you by attempting to use your application with a browser that is too old to support the necessary technologies. Alternatively, a visitor’s browser may have JavaScript and/or ActiveX disabled (for security or other reasons).
It is unfortunate if an Ajax application should break down under these conditions.
At the least, the occurrence of obvious errors (such as a failure to create an instance of the XMLHTTPRequest
object) should be reported to the user. If the Ajax application is so complex that it cannot be made to automatically revert to a non-Ajax mode of operation, perhaps the user can at least be redirected to a non-Ajax version of the application.
You can detect whether JavaScript is unavailable by using the |
<noscript> |
Search engines gather information about websites through various means, an important one being the use of automated programs called spiders.
Spiders, as their name suggests, “crawl the web” by reading web pages and following links, building a database of content and other relevant information about particular websites. This database, better known as an index, is queried by search engine visitors using their keywords and phrases and returns suggestions of relevant pages for them to visit.
This can create a problem for highly dynamic sites, which rely on user interaction (rather than passive surfing) to invoke the loading of new content delivered on-demand by the server. The visiting spider may not have access to the content that would be loaded by dynamic means and therefore never gets to index it.
The problem can be exacerbated further by the use of Ajax, with its tendency to deliver even more content in still fewer pages.
It would seem wise to ensure that spiders can index a static version of all relevant content somewhere on the site. Because spiders follow links embedded in pages, the provision of a hypertext linked site map can be a useful addition in this regard.
Without careful design, it may not be apparent to users which items on the page they can click on or otherwise interface with to make something happen.
It is worth trying to use a consistent style throughout an application to show which page elements cause server requests or some other dynamic activity. This is somewhat reminiscent of the way that hypertext links in HTML pages tend to be styled differently than plain text so that it’s clear to a user that they perform an additional function.
At the expense of a little more coding effort, instructions and information about active elements can be incorporated in ToolTip-style pop-ups. This is, of course, especially important when a click on an active link can have a major effect on the application’s state. Figure 24.1 shows an example of such a pop-up information box.
FIGURE 24.1 Pop-up information helps users to understand interfaces.
Attractive as Ajax undoubtedly is for improving web interfaces, you need to accept that there are many situations where the use of Ajax detracts from the user experience instead of adding to it.
This is especially true where the page-based interface metaphor is perfectly adequate for, perhaps even of greater relevance to, the content and style of the site. Text-based sites with subjects split conveniently into chapter-styled pages can often benefit as much from intelligently designed hyperlinking as they can from the addition of Ajax functionality.
Small sites in particular may struggle to get sufficient benefit from an Ajax interface to balance the associated costs of additional code and added complexity.
Ajax does not itself seem to present any security issues that are not already present when designing web applications. It is notable, however, that Ajax-enhanced applications tend to contain more client-side code than they did previously.
Because the content of client-side code can be viewed easily by any user of the application, it is important that sensitive information not be revealed within it. In this context, sensitive information is not limited to such things as usernames and passwords (though they are, of course, sensitive), but also includes business logic. Make the server-side scripts responsible for carrying out such issues as database connection. Validate data on the server before applying it to any important processing.
It will be clear from the content of this book that the various browsers behave differently in their implementation of JavaScript. The major difference in the generation of XMLHTTPRequest
object instances between Microsoft and non-Microsoft browsers is a fundamental example, but there is a host of minor differences, too.
The DOM, in particular, is handled rather differently, not only between browsers but also between different versions of the same browser. CSS implementation is another area where minor differences still proliferate.
Although it has always been important to test new applications on various browsers, this is perhaps more important than ever when faced with the added complexity of Ajax applications.
Hopefully browsers will continue to become more standards-compliant, but until then test applications on as many different platforms and with as many different browsers as possible.
All the dynamic interactivity in the world won’t correct a web application with a design that is fundamentally flawed.
All the tenets of good web design still apply to Ajax applications:
Write for multiple browsers and validate your code.
Comment and document your code well so that you can debug it later.
Use small graphics wherever possible so that they load quickly.
Make sure that your choices of colors, backgrounds, font sizes, and styles don’t make pages difficult to read.
The W3C offers a free online validator at http://validator.w3.org/.
Some of these have been alluded to in various chapters, but it’s worth grouping them here. These are probably the most common programming issues that Ajax developers bump up against at some time or other!
GET
RequestsMaking repeated GET
requests to the same URL
can often lead to the response coming not from the server but from the browser cache. This problem seems especially significant when using Internet Explorer.
Although in theory this can be cured with the use of suitable HTTP headers, in practice the cache can be stubborn.
An effective way of sidestepping this problem is to add a random element to the URL to which the request is sent; the browser interprets this as a request to a different page and returns a server page rather than a cached version.
In the text we achieved this by adding a random number. Another approach favored by many is to add a number derived from the time, which will of course be different every time:
var url = “serverscript.php”+”?rand=”+new Date().getTime();
Receiving a Permission Denied error usually means that you have fallen foul of the security measure preventing cross-domain requests from being made by an XMLHTTPRequest
object.
Calls must be made to server programs existing in the same domain as the calling script.
Be careful that the domain is written in exactly the same way. Somedomain.com may be interpreted as referring to a different domain from www.somedomain.com, and permission will be denied.
When constructing queries for GET
or POST
requests, remember to escape variables that could contain spaces or other nontext characters. In the following code, the value idValue
has been collected from a text input field on a form, so we escape it to ensure correct encoding:
http.open(“GET”, url + escape(idValue) + “&rand=” + myRandom, true);
Ajax undoubtedly has the potential to greatly improve web interfaces. However, the paradigm change from traditional page-based interfaces to highly dynamic applications has created a few potholes for developers to step into. In this chapter we’ve tried to round up a few of the better-known ones.
Some of these issues have already been encountered in the other chapters in this book, whereas others will perhaps not become apparent until you start to develop real-world applications.
This chapter concludes Part V, “More Complex Ajax Technologies.” If you have followed the chapters through to this point, you will by now have a good grip on the fundamentals of the XMLHTTPRequest
object, JavaScript, XML, and the Document Object Model, and be capable of creating useful Ajax applications from first principles.
Fortunately, you don’t have to always work from first principles. Many open source and commercial projects on the Internet offer a wide variety of Ajax frameworks, tools, and resources.
Part VI, “Ajax Tools and Resources,” of the book concludes our journey through Ajax development by looking at some of these resources and their capabilities.
18.189.182.96