Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning JavaScript With DOM Scripting And Ajax - From Novice To Professional (2006)

.pdf
Скачиваний:
80
Добавлен:
17.08.2013
Размер:
17.27 Mб
Скачать

296

C H A P T E R 7 J A V A S C R I P T A N D U S E R I N T E R A C T I O N : N A V I G A T I O N A N D F O R M S

The main difference in the script is that you have to target each input element you want to disable individually. In the case of the radio buttons, this means that you have to go through a loop. The changes in the script are highlighted in bold and should be self-explanatory:

dynamicFormDisable.js

df = {

hideClass : 'hide', letterOption : 'newsletter', subjectOption : 'subject', init : function() {

if( !document.getElementById || !document.createTextNode ){ return;

}

df.news = document.getElementById( df.letterOption ); df.subject = document.getElementById( df.subjectOption ); if(!df.subject || !df.news){ return; }

df.newsOpt = DOMhelp.closestSibling( df.news.parentNode, 1 ); df.newsOpt = df.newsOpt.getElementsByTagName( 'input' ); for( var i = 0; i < df.newsOpt.length; i++ ){

df.newsOpt[i].disabled = 1;

}

df.subjectOpt = DOMhelp.closestSibling( df.subject.parentNode, 1); df.subjectOpt = df.subjectOpt.getElementsByTagName( 'input' )[0]; df.subjectOpt.disabled = 1;

DOMhelp.addEvent( df.news, 'click', df.letterChange, false ); DOMhelp.addEvent( df.subject, 'change', df.subjectChange, false );

},

letterChange : function( e ){ var i;

var t = DOMhelp.getTarget( e ); var disable = t.checked ? null: 1 ;

for( i = 0; i < df.newsOpt.length; i++ ) { df.newsOpt[i].disabled = disable;

}

},

subjectChange : function( e ){ var t = DOMhelp.getTarget( e ); if( t.selectedIndex == 5 ) {

df.subjectOpt.disabled = null; df.subjectOpt.focus();

}else { df.subjectOpt.disabled = 1;

}

}

}

DOMhelp.addEvent( window, 'load', df.init, false );

C H A P T E R 7 J A V A S C R I P T A N D U S E R I N T E R A C T I O N : N A V I G A T I O N A N D F O R M S

297

The practical upshot of using disabled is that these elements cannot be reached via tabbing any longer either—something that is still possible with elements that are hidden (unless you hide them by setting display to none as shown earlier in the site navigation section).

Custom Form Elements

Given enough skill and testing time, you can use JavaScript to extend the normal form controls browsers provide the user with your own custom controls and even make them keyboard accessible. Especially in web application development, this might be a true necessity.

I won’t go into developing your own custom elements here, but I will touch on the subject in Chapter 11 again. For now, you can take a look at what the development teams at Yahoo (http://developer.yahoo.com/yui/slider/examples/slider.html) and Mozilla (http:// www.mozilla.org/access/dhtml/#examples) have come up with and give out for free.

Summary of Forms and JavaScript

I hope this gave you insight as to what is possible with forms and JavaScript. You have learned about the different properties and methods of forms themselves and each of the elements that they may contain with their individual properties and methods. You’ve seen in detail how to deal with select boxes and how you could make a form more dynamic by hiding elements that are dependent on others and only showing them when the other elements are activated or have the right value.

Things to Remember About Forms and JavaScript

Try not to go overboard on what you can do with forms. See whether the form is still usable with a keyboard once you’re done spicing it up. In particular, longer forms are more likely to be filled out by tabbing from field to field rather than by clicking the different elements and then editing them.

Don’t automatically submit a form with an event handler—forms can be submitted by clicking the Submit button or by hitting Enter. Don’t take these options away from the user.

While the older form collections forms and elements are not up-to-date DOM scripting techniques (as they are HTML dependent, whereas all the other DOM methods could also be applied to an XML string), they might be the easier option to use on generic or generated forms where you cannot control the IDs or the number of elements. Looping through one elements list is a lot easier than looping through all child elements of a form and comparing them with the possible element names or looping through the input, textarea, and select element collections individually.

Summary

You now should be able to handle the most common uses of JavaScript and come back to this and the previous chapter when you need to refresh your memory of how to deal with images, windows, navigation, and forms.

298

C H A P T E R 7 J A V A S C R I P T A N D U S E R I N T E R A C T I O N : N A V I G A T I O N A N D F O R M S

In the next chapter, we will leave the world of browser and client-side scripting and focus on how we can make JavaScript talk to the back end and server-side scripts. This will also enable you to take a look at that new kid on the scripting block: Ajax.

C H A P T E R 8

■ ■ ■

Back-End Interaction with Ajax

You finally reached the chapter where I am going to talk about the new amazing JavaScriptrelated phenomenon, Ajax. The good news is that you can use Ajax to create really nice, slick interfaces, and you can extend JavaScript’s reach much further than the browser and the currently displayed document.

The not-so-good news is that Ajax depends on the XMLHTTPRequest, XHR object for short (or its Microsoft equivalent), and that one has “HTTP” written all over it. What this means is that you cannot use any Ajax examples without a server, and furthermore you will have to have some basic knowledge of server-side scripting to use Ajax (unless you use one of the out-of- the-box packages available—more on those in the “Summary” section of the chapter).

It also means that using Ajax robs JavaScript of one of its strengths: to be able to create interfaces that work offline and on the file system of a computer or even from a CD or memory stick. However, the benefits of Ajax make up for this.

If you don’t want to transfer files back and forth between your local computer and a remote computer to test your code, the best option is to install a local server. This is not as tough as it seems at first glance, as nowadays there are a lot of prepackaged servers available (it was a nightmare in the 1990s, especially on Windows).

My personal favorite is XAMPP, which can be downloaded at http://www.apachefriends.org/. You can get an installer and follow the instructions to have your own server up and running in a matter of minutes.

XAMPP installs Apache 2, MySQL, PHP, and all the add-ons you will ever need and is available for many platforms. It also comes with an FTP and e-mail server, a statistics package, and many more options, and it is constantly kept up-to-date by the maintainers of Apache Friends (http://www.apachefriends.org). Oh and yes, it is free, of course.

Tip Again, to avoid frustration with the rest of the chapter, you should try out for yourself the many code examples in this chapter to see what I am talking about. The difference in comparison with the other chapters is that the code examples will not work locally on a computer on the file system; they require a server, as Ajax needs the HTTP protocol to work. If you don’t want to install a server but you are online, you can go to this book’s homepage at http://www.beginningjavascript.com/ where you’ll be able to see all the code examples in action.

299

300

C H A P T E R 8 B A C K - E N D I N T E R A C T I O N W I T H A J A X

When and if you install XAMMP, you can unpack the chapter examples in a directory— called, for example, jsbook—in the htdocs directory of the server installation, which could be c:\xammp\htdocs\. To see the examples, you open a browser and type in http://localhost/ jsbook/ as the location.

Tip In addition to the official help FAQs at http://www.apachefriends.org/en/faq-xampp.html, there is also a nice step-by-step explanation of how to install XAMPP (and WordPress) on a computer running Windows XP available at http://www.tamba2.org.uk/wordpress/xampp/.

Household Cleaning Liquid, Football Club, or Flash Gordon’s Spacecraft: What Is Ajax?

Ajax stands for Asynchronous JavaScript and XML, a term that was coined by Jesse James Garrett at Adaptive Path in February 2005 (http://www.adaptivepath.com/publications/essays/ archives/000385.php). It describes a methodology of developing web applications in a way different from the traditional one.

According to the article, traditional web apps and sites work synchronously—every time you follow a link, or when you submit a form, the browser sends the data to the server, the server (hopefully) responds, and the whole page gets refreshed.

Note This is not necessarily true, as older web apps like the Microsoft Outlook web interface work with frames and only reload smaller parts of the whole interface that way, but let’s not be picky; and for heaven’s sake let frames be a thing of the past when web connection speeds were below the 56K of a standard modem.

Ajax applications work asynchronously, which means that you send data back and forth between the user agent and the server without reloading the whole page. You replace only the parts of the page that change. You can also send several requests out and go on scrolling and using the page while the other parts load in the background.

One good comparison is that Ajax is to traditional web pages what instant messaging is to e-mails: immediate feedback, with no long waiting times and with more options to communicate. Figure 8-1 shows the flow of Ajax applications in comparison to traditional web sites and web applications.

 

 

 

C H A P T E R 8 B A C K - E N D I N T E R A C T I O N W I T H A J A X

301

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 8-1. Ajax vs. traditional request

At first glance, this appears to add an extra layer of complexity to the whole matter. However, the really cool thing about it is that the communication between the Ajax engine and the browser happens via JavaScript and not via page reloads.

In practical terms, this means for the end user less waiting for pages to load and render, and easier interaction with the page, as you can request data and still read the text or look at the other content on the page.

This makes for a much slicker interface, as you could, for example, give feedback on a login form without changing the whole site while being able to test for the right entries on the server or in a database.

Let’s have a go at a simple example. The demo file exampleXHR.html uses Ajax (well, without the X, as there is no XML involved) to load and display files from the server when the user clicks a link as shown in Figure 8-2.

302

C H A P T E R 8 B A C K - E N D I N T E R A C T I O N W I T H A J A X

Figure 8-2. Loading external files via Ajax

The magic wand behind all of this is an object called XMLHttpRequest, or XHR for short. This is a nonstandard object insofar as it is not part of an official standard on the W3C site (it is a working draft at the moment: http://www.w3.org/TR/XMLHttpRequest/), but it is supported across all modern browsers (Safari, Mozilla/Firefox, Opera). MSIE does not support XHR, but uses an ActiveX control instead. The good news is that the ActiveX control works the same way.

Caution The problem with this is when a user has JavaScript enabled but ActiveX disabled in MSIE, he won’t be able to experience your Ajax efforts. Keep this in mind if you create Ajax solutions and get user bug reports.

C H A P T E R 8 B A C K - E N D I N T E R A C T I O N W I T H A J A X

303

Let’s go through the example step by step so you can see what the different parts do. The HTML contains links pointing to text files and calls the simplexhr.doxhr method with two parameters: an ID of an HTML element to send the text to and the URL of the text:

exampleXHR.html (excerpt)

<li>

<a href="perfect_day.txt"

onclick="simplexhr.doxhr( 'txtcontainer1', this.href ); return false;">

Perfect Day </a>

</li>

<li>

<a href="great_adventure.txt"

onclick="simplexhr.doxhr( 'txtcontainer1', this.href ); return false;">

Great Adventure </a>

</li>

Note Notice that these links are not totally unobtrusive and up to the standard of the rest of the code examples in this book, but at least they work without JavaScript—the browser will simply show the text files when scripting is not available. It is very tempting, especially when using out-of-the-box Ajax libraries, to create scripting-dependent links. No matter how cool the technology is, this is never a good idea.

simpleXHR.js

simplexhr = {

doxhr : function( container, url ) {

if( !document.getElementById || !document.createTextNode) { return;

}

simplexhr.outputContainer = document.getElementById( container ); if( !simplexhr.outputContainer ){ return; }

304

C H A P T E R 8 B A C K - E N D I N T E R A C T I O N W I T H A J A X

The script starts by checking for the DOM and whether the element you want to write content into is available. If it is, it gets stored in a property called outputContainer to make it available for all other methods in the script.

simpleXHR.js (continued)

var request; try{

request = new XMLHttpRequest();

}catch ( error ) { try {

request = new ActiveXObject( "Microsoft.XMLHTTP" );

}catch ( error ) { return true;

}

}

Define a new variable called request and use the try and catch construct to see which XHR version is supported. Try assigning a new XMLHttpRequest() for Mozilla and Safari; if that is not supported, an error occurs that triggers the catch statement (you can learn more about try and catch() in the appendix of this book). This one tries to assign the Microsoft ActiveX object instead. If that is not available either, the method returns true, which means the browser will just follow the link and show the text in the browser.

If the assignment was successful, you have a new XMLHttpRequest object at your disposal.

Note For a complete list of methods, handlers, and properties of the XMLHttpRequest object, you can consult the documentation at XULPlanet (http://www.xulplanet.com/references/objref/ XMLHttpRequest.html) or Microsoft (http://msdn.microsoft.com/library/en-us/xmlsdk/html/ xmobjpmexmlhttprequest.asp), respectively.

C H A P T E R 8 B A C K - E N D I N T E R A C T I O N W I T H A J A X

305

The first step is to call the open() method to start the connection with the server and retrieve or send data. The open() method takes five parameters, three of which are optional:

request = open(requestMethod, url[, sync, [name, [password]]]);

The requestMethod parameter can be (among some other options that would exceed the scope of this chapter) either GET or POST, and corresponds to the method attribute of a FORM element. The GET method is much easier, but also less secure, just as it is with forms and server-side data handling (data sent via GET is visible in the URL and can be easily manipulated there by others).

The url parameter is the location of the file on your server.

Note XMLHttpRequest does not allow you to load content from other servers, as that would be a big security problem. Imagine any JavaScript embedded into an e-mail or web site being able to send off any data from your computer or retrieve more code from a server. There is a way to load third-party content, though, by using a proxy script on the server—more on that later in the XML example.

The sync parameter is optional and is a Boolean that defines whether the request should be sent asynchronously or synchronously. It is hard-wired to true—which means the request will be sent asynchronously. Synchronous requests would lock up the browser.

The name and password parameters are optional and only necessary when the file you try to call requires user authentication.

In this case, you will retrieve files only from the server, and to do that you use GET as the request method and the file’s location as the url parameter, omitting the optional parameters.

simpleXHR.js (continued)

request.open( 'get', url );