scripting launguage assignment

User Generated

havdhrylzr

Computer Science

Description


Been in hospital, running behind and need this as soon as possible, if you can do it please let me know . thank you.

Javascript.The.Web.Technologies.Series.5th.Edition-PTM.pdf


Project 6.docx

Unformatted Attachment Preview

JAVASCRIPT This page intentionally left blank FIFTH EDITION JAVASCRIPT DON GOSSELIN Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States JavaScript, Fifth Edition Don Gosselin Marie Lee: Executive Editor Acquisitions Editor: Amy Jollymore Senior Product Manager: Alyssa Pratt Development Editor: Ann Shaffer Editorial Assistant: Zina Kresin Senior Content Project Manager: Jill Braiewa Art Director: Marissa Falco Quality Assurance Testers: John Freitas, Serge Palladino, Danielle Shaw Text Designer: Shawn Girsberger © 2011 Course Technology, Cengage Learning ALL RIGHTS RESERVED. No part of this work covered by the copyright herein may be reproduced, transmitted, stored or used in any form or by any means graphic, electronic, or mechanical, including but not limited to photocopying, recording, scanning, digitizing, taping, Web distribution, information networks, or information storage and retrieval systems, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the publisher. For product information and technology assistance, contact us at Cengage Learning Customer & Sales Support, 1-800-354-9706 For permission to use material from this text or product, submit all requests online at cengage.com/permissions Further permissions questions can be emailed to permissionrequest@cengage.com Cover Image: © CSA Images Print Buyer: Julio Esperas Library of Congress Control Number: 2009942878 Copyeditor: Jeri Freedman, Foxxe Editorial Services ISBN-13: 978-0-538-74887-2 ISBN-10: 0-538-74887-7 Proofreader: Vicki Zimmer Course Technology 20 Channel Center Street Boston, MA 02210 USA Indexer: Rich Carlson Compositor: Integra Software Services Some of the product names and company names used in this book have been used for identification purposes only and may be trademarks or registered trademarks of their respective manufacturers and sellers. Any fictional data related to persons or companies or URLs used throughout this book is intended for instructional purposes only. At the time this book was printed, any such data was fictional and not belonging to any real persons or companies. Course Technology, a part of Cengage Learning, reserves the right to revise this publication and make changes from time to time in its content without notice. The programs in this book are for instructional purposes only. They have been tested with care, but are not guaranteed for any particular intent beyond educational purposes. The author and the publisher do not offer any warranties or representations, nor do they accept any liabilities with respect to the programs. Cengage Learning is a leading provider of customized learning solutions with office locations around the globe, including Singapore, the United Kingdom, Australia, Mexico, Brazil, and Japan. Locate your local office at: www.cengage.com/global Cengage Learning products are represented in Canada by Nelson Education, Ltd. To learn more about Course Technology, visit www.cengage.com/coursetechnology Purchase any of our products at your local college store or at our preferred online store: www.CengageBrain.com Printed in the United States of America 1 2 3 4 5 6 7 16 15 14 13 12 11 10  I dedicate this book to my late grandparents, John and Edith Howe, for teaching me how to laugh. Brief Contents vi Pref ace . . . . . . . . . . . . . . . . xvii CHAPT ER 1 I nt ro duct i o n t o J av aScri pt CHAPT ER 2 Wo r ki ng w i t h Functi ons, Data Ty pes, and Oper at o rs . . . . . . . . . . . . . . . . 72 CHAPT ER 3 B ui ldi ng A rr ay s and Control Structures . . . 135 CHAPT ER 4 M ani pul at in g t he Browser Obj ect Model . . . 190 CHAPT ER 5 Val idat i ng F orm Data wi th Jav aScri pt . . . . 245 CHAPT ER 6 U si ng Obj ect - Ori ented Jav aScri pt . . . . . 311 CHAPT ER 7 M ani pul at in g Dat a i n Stri ngs and Array s . . 373 CHAPT ER 8 Debu g g in g and E rror Handl i ng. . . . . . . 440 CHAPT ER 9 M anag i ng S tat e I nformati on and Securi ty . . 510 CHAPT ER 10 I nt ro duct i o n t o t he Document Obj ect M o del (DOM) . . . . . . . . . . . . . . 574 CHAPT ER 11 Creat in g Dynam i c HTML (DHTML) CHAPT ER 12 U pdat in g Web P ages wi th AJAX . . . . . . 679 APPEN DIX A Bu il din g a Web Dev el opment Env i ronment . . 750 APPEN DIX B I nt ro duct i o n t o P HP . . . . . . . . . . . 772 APPEN DIX C Wo rk in g w it h Wel l - Formed Web Pages APPEN DIX D J av aScr ipt R ef erence APPEN DIX E So l ut i o ns t o Sho r t Qui z z es . . . . . . . . 830 I ndex . . . . . . . . . 1 . . . . . 624 . . . 798 . . . . . . . . . . 809 . . . . . . . . . . . . . . . . . 885 Contents vii P ref ace CHAP TER 1 . . . . . . . . . . . . . . . . I nt ro duct i on t o Jav aScri pt xvii . . . . . . . . . Introduction to the World Wide Web . . . . . . . . . . Understanding Web Browsers . . . . . . . . . . . . Creating Web Pages . . . . . . . . . . . . . . . . Basic HTML Syntax. . . . . . . . . . . . . . . . . Creating an HTML Document . . . . . . . . . . . . Working with XHTML and Well-Formed Web Pages . . . Introduction to Web Development . . . . . . . . . . . Understanding Client/Server Architecture . . . . . . JavaScript and Client-Side Scripting . . . . . . . . . Understanding Server-Side Scripting . . . . . . . . . Should You Use Client-Side or Server-Side Scripting? . Adding JavaScript to Your Web Pages . . . . . . . . . Using the Element. . . . . . . . . . . . Understanding JavaScript Objects . . . . . . . . . . Using the write() and writeln() Methods . . . . Case Sensitivity in JavaScript . . . . . . . . . . . . Adding Comments to a JavaScript Program. . . . . . Writing Basic JavaScript Code . . . . . . . . . . . . Using Variables . . . . . . . . . . . . . . . . . . Assigning Variable Names . . . . . . . . . . . . . Building Expressions . . . . . . . . . . . . . . . . Understanding Events . . . . . . . . . . . . . . . Structuring JavaScript Code . . . . . . . . . . . . . Including a Element for Each Code Section Placing JavaScript in the Document Head or Document Body . . . . . . . . . . . . . . . . Creating a JavaScript Source File . . . . . . . . . . Validating Web Pages . . . . . . . . . . . . . . . Writing Valid JavaScript Code . . . . . . . . . . . . 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 . 4 . 5 . 5 . 9 . 9 . 14 . 15 . 17 . 19 . 20 . 22 . 22 . 23 . 24 . 28 . 28 . 30 . 30 . 30 . 35 . 35 . 41 . 41 . . . . . . . . . 42 . 43 . 45 . 46 CONTENTS Summing Up . . . . . Comprehension Check . Reinforcement Exercises Discovery Projects . . . viii CHAPTER 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 . 52 . 56 . 68 Wo r ki ng w i t h Functi ons, Data Ty pes, an d Operat o rs . . . . . . . . . . . . . . 72 Working with Functions . . . . . . . . . Defining Functions . . . . . . . . . . Calling Functions. . . . . . . . . . . Understanding Variable Scope. . . . . Using Built-in JavaScript Functions . . . Working with Data Types . . . . . . . . Understanding Numeric Data Types . . Using Boolean Values . . . . . . . . Working with Strings . . . . . . . . . Using Operators to Build Expressions . . Arithmetic Operators . . . . . . . . . Assignment Operators . . . . . . . . Comparison and Conditional Operators. Logical Operators . . . . . . . . . . Special Operators . . . . . . . . . . Understanding Operator Precedence . . Summing Up . . . . . . . . . . . . . Comprehension Check . . . . . . . . . Reinforcement Exercises . . . . . . . . Discovery Projects . . . . . . . . . . . CHAPTER 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 . 73 . 76 . 79 . 81 . 83 . 85 . 88 . 89 . 95 . 97 105 107 111 113 114 117 118 121 132 B ui ldi ng A rr ay s and Control Structures . . . 135 Storing Data in Arrays . . . . . . . . . . Declaring and Initializing Arrays . . . . . Accessing Element Information . . . . . Modifying Elements . . . . . . . . . . Determining the Number of Elements in an Making Decisions . . . . . . . . . . . . if Statements . . . . . . . . . . . . if . . . else Statements . . . . . . . Nested if and if . . . else Statements switch Statements . . . . . . . . . . Repeating Code . . . . . . . . . . . . . while Statements. . . . . . . . . . . do . . . while Statements . . . . . . . . . . . . . . . . . . . Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 136 138 139 139 140 140 146 149 154 158 158 165 for Statements . . . . . . . Using CONTINUE Statements to Summing Up . . . . . . . . . Comprehension Check . . . . . Reinforcement Exercises . . . . Discovery Projects . . . . . . . CHAP TER 4 . . . . . . . . . Restart Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 171 173 174 179 187 M ani pul at ing t he Browser Obj ect Model . . . 190 Understanding the Browser Object Model . . . . . . . . The Document Object . . . . . . . . . . . . . . . . Referencing JavaScript Objects . . . . . . . . . . . . Manipulating the Browser with the Window Object . . . . Understanding Windows and Events . . . . . . . . . . Referring to Frames and Windows . . . . . . . . . . . Opening and Closing Windows . . . . . . . . . . . . . Working with Timeouts and Intervals . . . . . . . . . . Working with the History, Location, and Navigator Objects . . . . . . . . . . . . . . . . . . . . . . . The History Object. . . . . . . . . . . . . . . . . The Location Object . . . . . . . . . . . . . . . . The Navigator Object . . . . . . . . . . . . . . . The Screen Object . . . . . . . . . . . . . . . . . Summing Up . . . . . . . . . . . . . . . . . . . . . Comprehension Check . . . . . . . . . . . . . . . . . Reinforcement Exercises . . . . . . . . . . . . . . . . Discovery Projects . . . . . . . . . . . . . . . . . . . CHAP TER 5 . . . . . . . . . . . . . . 191 192 193 197 199 206 206 217 . . . . . . . . . 220 220 222 224 225 228 229 233 242 Val idat i ng Fo rm Data wi th Jav aScri pt . . . . 245 Understanding Forms . . . . . . . . Understanding the Element . Working with Form Controls . . . . . Using JavaScript with Forms . . . . Working with Input Fields . . . . . . . Input Field Objects . . . . . . . . . Text Boxes . . . . . . . . . . . . Password Boxes . . . . . . . . . . Push Buttons . . . . . . . . . . . Radio Buttons . . . . . . . . . . . Check Boxes . . . . . . . . . . . Creating Selection Lists . . . . . . . Menu Options . . . . . . . . . . . The Select and Option Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246 249 251 252 255 257 259 264 266 268 272 276 277 280 ix CONTENTS Adding Options to a Selection List . . . Removing Options from a Selection List Changing Options in a Selection List . . Validating Submitted Data . . . . . . . Validating Text and Password Boxes . . Validating Radio Buttons . . . . . . . Validating Check Boxes . . . . . . . . Validating Selection Lists . . . . . . . Summing Up . . . . . . . . . . . . . Comprehension Check . . . . . . . . . Reinforcement Exercises . . . . . . . . Discovery Projects . . . . . . . . . . . x CHAPTER 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 285 286 290 292 294 296 297 298 299 302 308 U si ng Obj ect - Ori ented Jav aScri pt . . . . . 311 Introduction to Object-Oriented Programming . . . . . Reusing Software Objects. . . . . . . . . . . . . What Is Encapsulation? . . . . . . . . . . . . . . Understanding Classes . . . . . . . . . . . . . . Using Built-In JavaScript Classes . . . . . . . . . Using the Date, Number, and Math Classes . . . . Manipulating the Date and Time with the Date Class Manipulating Numbers with the Number Class . . . Performing Math Functions with the Math Class . . Defining Custom JavaScript Objects . . . . . . . . . Declaring Basic Custom Objects. . . . . . . . . . Defining Constructor Functions . . . . . . . . . . Working with Object Properties . . . . . . . . . . Creating Methods . . . . . . . . . . . . . . . . Using the prototype Property . . . . . . . . . . Summing Up . . . . . . . . . . . . . . . . . . . Comprehension Check . . . . . . . . . . . . . . . Reinforcement Exercises . . . . . . . . . . . . . . Discovery Projects . . . . . . . . . . . . . . . . . CHAPTER 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 312 314 316 317 319 319 332 337 340 341 344 345 353 357 360 361 364 371 M ani pul at in g Dat a i n Stri ngs and Array s . . 373 Manipulating Strings . . . . . . . . . . . . . . . Formatting Strings . . . . . . . . . . . . . . . Counting Characters in a String . . . . . . . . . Finding and Extracting Characters and Substrings Replacing Characters and Substrings . . . . . . Combining Characters and Substrings . . . . . . Comparing Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 376 380 381 386 386 387 Working with Regular Expressions . . . . . . Defining Regular Expressions in JavaScript . Using Regular Expression Methods . . . . Writing Regular Expression Patterns . . . . Setting Regular Expression Properties . . . Manipulating Arrays . . . . . . . . . . . . Finding and Extracting Elements and Values Manipulating Elements . . . . . . . . . . Sorting and Combining Arrays . . . . . . . Converting Between Strings and Arrays . . . Summing Up . . . . . . . . . . . . . . . Comprehension Check . . . . . . . . . . . Reinforcement Exercises . . . . . . . . . . Discovery Projects . . . . . . . . . . . . . CHAP TER 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390 391 392 393 402 404 407 409 414 417 422 423 426 437 Debu g g in g and Error Handl i ng. . . . . . . 440 Introduction to Debugging . . . . . . . . . . . . . Understanding Syntax Errors . . . . . . . . . . . Handling Run-Time Errors . . . . . . . . . . . . . Identifying Logic Errors . . . . . . . . . . . . . . Interpreting Error Messages . . . . . . . . . . . Using Basic Debugging Techniques . . . . . . . . . Writing Good Code . . . . . . . . . . . . . . . . Tracing Errors with the window.alert() Method . Tracing Errors with the write() and writeln() Methods . . . . . . . . . . . . . . . . . . . . Using Comments to Locate Bugs . . . . . . . . . Combining Debugging Techniques . . . . . . . . . Tracing Errors with Debugging Tools. . . . . . . . . Understanding the JavaScript Debugger and JScript Debugger Windows . . . . . . . . . . . . . . . Setting Breakpoints . . . . . . . . . . . . . . . Stepping through Your Scripts . . . . . . . . . . Clearing Breakpoints . . . . . . . . . . . . . . . Tracing Variables and Expressions . . . . . . . . . Examining the Call Stack . . . . . . . . . . . . . Handling Exceptions and Errors . . . . . . . . . . . Throwing Exceptions . . . . . . . . . . . . . . . Catching Exceptions . . . . . . . . . . . . . . . Executing Final Exception Handling Tasks . . . . . Implementing Custom Error Handling . . . . . . . Additional Debugging Techniques . . . . . . . . . . Checking XHTML Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443 443 444 444 445 451 452 452 . . . . . . . . . . . . 455 460 461 464 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465 469 473 474 475 480 481 482 483 483 486 489 490 xi CONTENTS Analyzing Logic . . . . . . . . . . . . . . . . Testing Statements with JavaScript URLs. . . . . Reloading a Web Page . . . . . . . . . . . . . Using a for...in Statement to Check Object Properties . . . . . . . . . . . . . . . . . . Identifying JavaScript Language and Browser Bugs Summing Up . . . . . . . . . . . . . . . . . . Comprehension Check . . . . . . . . . . . . . . Reinforcement Exercises . . . . . . . . . . . . . Discovery Projects . . . . . . . . . . . . . . . . xii CHAPTER 9 . . . . . . . . . . . . . . . . . . . . . . . . 493 494 496 497 501 508 M anag i ng S tat e I nformati on and Securi ty . . 510 Understanding State Information . . . . . . . . . Saving State Information with Hidden Form Fields . Saving State Information with Query Strings . . . Saving State Information with Cookies . . . . . . . Creating and Modifying Cookies . . . . . . . . . Reading Cookies with JavaScript . . . . . . . . Deleting Cookies with JavaScript . . . . . . . . Understanding Security Issues . . . . . . . . . . Secure Coding with JavaScript . . . . . . . . . JavaScript Security Concerns . . . . . . . . . . The Same Origin Policy . . . . . . . . . . . . . Summing Up . . . . . . . . . . . . . . . . . . Comprehension Check . . . . . . . . . . . . . . Reinforcement Exercises . . . . . . . . . . . . . Discovery Projects . . . . . . . . . . . . . . . . CHAPTER 10 . . . . 490 . . . . 492 . . . . 492 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511 512 527 536 537 545 548 549 549 550 551 555 556 559 572 I nt ro duct i o n t o t he Document Obj ect M o del (DOM) . . . . . . . . . . . . . . 574 Understanding the HTML Document Object Model . . HTML DOM Document Object Methods . . . . . HTML DOM Document Object Properties . . . . Opening and Closing the Document Object . . . Using the Image Object . . . . . . . . . . . . . Animation with the Image Object . . . . . . . . Image Caching. . . . . . . . . . . . . . . . . Accessing Document Elements . . . . . . . . . . Accessing Elements by Name . . . . . . . . . . Accessing Elements by Tag Name . . . . . . . . Accessing Elements by ID . . . . . . . . . . . Modifying Elements with the innerHTML Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575 576 577 578 582 585 592 597 597 600 602 603 Summing Up . . . . . Comprehension Check . Reinforcement Exercises Discovery Projects . . . CHAP TER 1 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creat in g Dy nami c HTML (DHTML) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605 607 610 621 . . . . . 624 Manipulating CSS with JavaScript . . . . . . . . . . . Modifying Styles with the this Reference . . . . . . Modifying Styles with Methods of the Document Object Checking Browser Compatibility . . . . . . . . . . . Understanding CSS Positioning . . . . . . . . . . . . Dynamic Positioning . . . . . . . . . . . . . . . . Traveling Animation . . . . . . . . . . . . . . . . Creating DHTML Menus. . . . . . . . . . . . . . . . Expandable Menus . . . . . . . . . . . . . . . . . Navigation Menus . . . . . . . . . . . . . . . . . Sliding Menus . . . . . . . . . . . . . . . . . . . Summing Up . . . . . . . . . . . . . . . . . . . . Comprehension Check . . . . . . . . . . . . . . . . Reinforcement Exercises . . . . . . . . . . . . . . . Discovery Projects . . . . . . . . . . . . . . . . . . CHAP TER 1 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625 625 630 633 634 635 637 643 643 648 654 658 659 663 677 U pdat in g Web Pages wi th AJAX . . . . . . 679 Introduction to AJAX . . . . . . . . . . . . . . Understanding AJAX’s Limitations . . . . . . . Accessing Content on a Separate Domain . . . Running AJAX from a Web Server . . . . . . . Overview of Creating an AJAX Script . . . . . . Working with HTTP . . . . . . . . . . . . . . . Understanding HTTP Messages . . . . . . . . Sending HTTP Requests . . . . . . . . . . . Receiving HTTP Responses . . . . . . . . . . Requesting Server Data . . . . . . . . . . . . Instantiating an XMLHttpRequest Object . . . . Opening and Sending a Request . . . . . . . . Receiving Server Data . . . . . . . . . . . . . Sending and Receiving Synchronous Requests and Responses . . . . . . . . . . . . . . Sending and Receiving Asynchronous Requests and Responses . . . . . . . . . . . . . . . Refreshing Server Data Automatically . . . . . Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680 685 686 691 692 693 694 696 697 702 703 707 711 . . . . . 713 . . . . . 719 . . . . . 722 . . . . . 725 xiii CONTENTS Summing Up . . . . . Comprehension Check . Reinforcement Exercises Discovery Projects . . . xiv APPEN DIX A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726 727 731 747 B ui ldi ng a Web Dev el opment Env i ronment . . 750 Building a Web Development Environment . . . . . . Understanding Binary and Source Code Installations . Getting Help . . . . . . . . . . . . . . . . . . . Installing and Configuring a Web Server . . . . . . . Installing and Running Apache on UNIX and Linux . . Installing and Running Apache on Windows . . . . . Installing and Running Internet Information Services on Windows Operating Systems . . . . . . . . . Installing and Controlling IIS on Windows Vista and Windows 7 . . . . . . . . . . . . . . . . . Testing Your Web Server . . . . . . . . . . . . . Configuring Apache . . . . . . . . . . . . . . . Configuring Internet Information Services . . . . . Installing PHP . . . . . . . . . . . . . . . . . . . Installing PHP on UNIX and Linux Systems Running Apache . . . . . . . . . . . . . . . . Installing PHP on Windows Running Apache or IIS . . Configuring Apache for PHP on UNIX/Linux Platforms Configuring PHP . . . . . . . . . . . . . . . . . APPEN DIX B . . . . . . . . . . . . . . . . . . . . . . 750 751 752 754 754 756 . . . 758 . . . . . . . . . . . . . . . 759 760 762 765 767 . . . . . . . . . . . . 767 769 770 771 I nt ro duct i o n t o P HP . . . . . . . . . . . 772 Creating Basic PHP Scripts . . . . . . . . . . . . . . . Creating PHP Code Blocks . . . . . . . . . . . . . . Displaying Script Results . . . . . . . . . . . . . . . Case Sensitivity in PHP . . . . . . . . . . . . . . . . Adding Comments to a PHP Script . . . . . . . . . . . Using Variables . . . . . . . . . . . . . . . . . . . . Working with Data Types . . . . . . . . . . . . . . . Understanding Variable Scope. . . . . . . . . . . . . Working with Operators, Functions, and Control Structures Working with PHP Strings . . . . . . . . . . . . . . . . Using String Operators . . . . . . . . . . . . . . . . Understanding Simple and Complex String Syntax . . . . Parsing Strings . . . . . . . . . . . . . . . . . . . Finding and Extracting Characters and Substrings . . . Replacing Characters and Substrings . . . . . . . . . . . . . . . . . . . . . . . . 772 773 773 774 775 775 776 776 777 777 777 778 779 779 781 Comparing Strings . . . . . . . . . Working with Arrays . . . . . . . . . Manipulating Elements . . . . . . . Manipulating Arrays . . . . . . . . Converting Between Strings and Arrays Handling Form Submissions. . . . . . Using Autoglobals . . . . . . . . . Validating Submitted Data . . . . . Working with Files . . . . . . . . . . Opening and Closing File Streams . . Writing Data to Files . . . . . . . . Reading Data from Files . . . . . . APPEN DIX C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Wo rk in g wi t h Wel l - Formed Web Pages XHTML Document Type Definitions (DTDs) . Transitional DTD . . . . . . . . . . . . Frameset DTD . . . . . . . . . . . . . Strict DTD. . . . . . . . . . . . . . . Writing Well-Formed Documents . . . . . . Using Phrase Elements . . . . . . . . . . Working with Cascading Style Sheets (CSS) CSS Properties . . . . . . . . . . . . Inline Styles . . . . . . . . . . . . . . Internal Style Sheets . . . . . . . . . . External Style Sheets . . . . . . . . . The Content-Type Element . . . . APPEN DIX D . . . . . . . . . . . . J avaS cri pt R ef erence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 781 782 783 785 787 788 788 790 792 792 794 796 . . . 798 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798 799 799 800 800 801 803 803 803 805 806 807 . . . . . . . . . . 809 Comment Types . . . . . . . . . Line Comments . . . . . . . . Block Comments . . . . . . . . JavaScript Reserved Words . . . . Events . . . . . . . . . . . . . JavaScript Events . . . . . . . Elements and Associated Events Primitive Data Types . . . . . . . JavaScript Escape Sequences . . Operators . . . . . . . . . . . . JavaScript Operator Types . . . Arithmetic Binary Operators. . . Arithmetic Unary Operators . . . Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809 809 809 810 810 810 811 811 812 812 812 813 813 813 xv CONTENTS Comparison Operators . . . . . . . Logical Operators . . . . . . . . . Operator Precedence . . . . . . . . Control Structures and Statements . . if Statements . . . . . . . . . . if...else Statements . . . . . . switch Statements . . . . . . . . while Statements. . . . . . . . . do...while Statements . . . . . for Statements . . . . . . . . . . for...in Statements . . . . . . . with Statements . . . . . . . . . break Statements. . . . . . . . . continue Statements . . . . . . . Built-In JavaScript Functions . . . . . Built-In JavaScript Classes . . . . . . Array Class . . . . . . . . . . . Date Class . . . . . . . . . . . . Math Class . . . . . . . . . . . . Number Class . . . . . . . . . . . String Class . . . . . . . . . . . Objects of the Browser Object Model . Document Object . . . . . . . . . History Object. . . . . . . . . . Location Object . . . . . . . . . Navigator Object . . . . . . . . Screen Object . . . . . . . . . . Window Object . . . . . . . . . . Objects of the Document Object Model Form Object . . . . . . . . . . . Image Object . . . . . . . . . . . Input Object . . . . . . . . . . . xvi APPEN DIX E . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814 814 815 815 815 815 816 816 816 816 816 816 816 817 817 817 817 818 819 820 821 822 822 823 824 824 825 825 826 826 827 828 S o lu t io n s t o Sho r t Qui z z es . . . . . . . . 830 I ndex . . . . . . . . . . . . . . . . . 885 Preface xvii JavaScript is a client-side scripting language that allows Web page authors to develop interactive Web pages and sites. Although JavaScript is considered a programming language, it is also a critical part of Web page design and authoring. This is because the JavaScript language “lives” within a Web page’s elements. The language is relatively easy to learn, allowing non-programmers to quickly incorporate JavaScript functionality into a Web page. In fact, because it is used extensively in the countless Web pages that are available on the World Wide Web, JavaScript is arguably the most widely used programming language in the world. JavaScript, Fifth Edition teaches Web page development with JavaScript for students with little programming or database experience. Although no prior programming experience is required, knowledge of HTML and Web page design is helpful, but not required. This book covers the basics of ECMAScript Edition 3, which is compatible with recent Web browsers including Mozilla Firefox and Microsoft Internet Explorer, along with advanced topics including object-oriented programming, the Document Object Model (DOM), and AJAX. Further, this book presents JavaScript techniques using XHTML-compatible Web pages. After you complete this course, you will be able to use JavaScript to build professional quality, dynamic Web sites. The Approach This book introduces a variety of techniques, focusing on what you need to know to start writing JavaScript programs. In each chapter, you perform tasks that let you use a particular technique to build JavaScript programs. The step-by-step tasks are guided activities that reinforce the skills you learn in the chapter and build on your learning experience by providing additional ways to apply your knowledge in new situations. In addition to step-by-step tasks, each chapter includes objectives, short quizzes, comprehension checks, and reinforcement exercises that highlight major concepts and let you practice the techniques you learn. At the end of each chapter, you will also P R E FA C E complete Discovery Projects that let you use the skills you learned in the chapter to write JavaScript programs on your own. xviii As with the last edition of this book, Web page examples and exercises are written in XHTML. Although you need to have a solid understanding of HTML to be successful with this book, you do not necessarily need to be an expert with XHTML. Because XHTML is almost identical to HTML, you can easily adapt any of your existing HTML skills to XHTML, and vice versa. Overview of This Book The examples and exercises in this book will help you achieve the following objectives: • Use JavaScript with well-formed Web pages • Work with JavaScript variables and data types and learn how to use the operations that can be performed on them. • Add functions, events, and control structures to your JavaScript programs • Write JavaScript code that controls the Web browser through the browser object model • Use JavaScript to make sure data was entered properly into form fields and to perform other types of preprocessing before form data is sent to a server • Include object-oriented programming techniques in your JavaScript programs • Manipulate data in strings and arrays • Trace and resolve errors in JavaScript programs • Save state information using hidden form fields, query strings, and cookies • Add animation and interactivity to your Web pages using the Document Object Model (DOM) and Dynamic HTML (DHTML) • Dynamically update Web pages with AJAX JavaScript presents twelve chapters that cover specific aspects of JavaScript programming. Chapter 1 discusses basic concepts of the World Wide Web, introduces XHTML documents, and covers the basics of how to add JavaScript to well-formed Web pages. How to write basic JavaScript code, including how to use variables, data types, expressions, operators, and events, is also discussed in Chapter 1. This early introduction of key JavaScript concepts gives students a framework for better understanding more advanced concepts and techniques later in this book, and allows them to work on more comprehensive projects from the start. Chapter 2 covers functions, data types, and how to build expressions. Chapter 3 explains how to store data in arrays and how to use structured logic in control structures and statements. Chapter 4 teaches how to use JavaScript to manipulate the Web browser using the Window, History, Location, Navigator, and Screen objects. Chapter 5 explains how to use JavaScript to make sure data was entered properly into form fields and how to perform other types of preprocessing before form data is sent to a server. Chapter 6 presents object-object oriented programming concepts, including how to use JavaScript’s built-in Array, Date, Number, and Math classes. Chapter 7 covers advanced techniques for manipulating data in strings and arrays. Chapter 8 provides a thorough discussion of debugging techniques, including how to use script debugging tools for Firefox and Internet Explorer. Chapter 9 explains how to save state information using hidden form fields, query strings, and cookies, and also briefly discusses JavaScript security issues. Chapter 10 and Chapter 11 teach how to add animation and interactivity to your Web pages using the Document Object Model (DOM) and Dynamic HTML (DHTML). Chapter 12 introduces the basics of how to use AJAX to dynamically update portions of a Web page with server-side data. What’s New in This Edition? The fifth edition includes the following important new features: • Significant revisions and improvements to the chapter projects and examples. • The use of professionally designed Web pages for chapter projects. The goal of this book is to teach Web page authoring techniques, not Web page design techniques. In the real world, Web page authors often (but not always) receive completed Web pages from a Web page designer. For this reason, students work with professionally designed Web pages that they would encounter in a business setting. • Instructions on working with XHTML moved to an appendix, providing a quick reference for students who need it, without slowing down general classroom instruction. • A new streamlined layout that makes it easier to locate information quickly. xix P R E FA C E • An introduction to the basics of JavaScript in Chapter 1 that gives students a framework for understanding more advanced concepts and techniques later in this book, and allows them to work on more comprehensive projects from the start. xx • An introduction to arrays in Chapter 3, “Building Arrays and Control Structures,” that provides a better context for learning about arrays and control structures. Features JavaScript, Fifth Edition is a superior textbook because it also includes the following features: CHAPTER OBJECTIVES: Each chapter begins with a list of the important concepts presented in the chapter. This list provides students with a quick reference to the contents of the chapter as well as a useful study aid. FIGURES AND TABLES: Plentiful screenshots allow students to check their screens against the desired output. Tables consolidate important material for easy reference. CODE EXAMPLES: Numerous code examples throughout each chapter are presented in any easy-to-read font, with key words shown in color. NEW TERMS: New terms are printed in boldface to draw the reader’s attention to new material. HELP: These margin notes provide more information about the task the student is currently performing. POINTER: These useful asides, located in the margin, provide students with practical advice and proven strategies related to the concept being discussed. They also contain cross-references to other sections in the book or to related Web sites. NOTE: These margin elements provide additional helpful information on specific techniques and concepts. CAREFUL: These cautionary notes point out troublesome issues related to a particular technique or concept. SHORT QUIZ: Several short quizzes are included in each chapter. These quizzes, consisting of three to five questions, help ensure students understand the major points introduced in the chapter. SUMMING UP: These brief overviews revisit the ideas covered in each chapter, providing students with a helpful study guide. COMPREHENSION CHECK: At the end of each chapter, a set of twenty review questions reinforce the main ideas introduced in the chapter. These questions help students determine whether or not they have mastered the concepts presented in the chapter. REINFORCEMENT EXERCISES: Although it is important to understand the concepts behind every technology, no amount of theory can improve on real-world experience. To this end, each chapter includes detailed Reinforcement Exercises that provide students with practical experience implementing technology skills in real-world situations. DISCOVERY PROJECTS: These end-of-chapter projects are designed to help students apply what they have learned to business situations, much like those a professional Web developer would encounter. They give students the opportunity to independently synthesize and evaluate information, examine potential solutions, and make decisions about the best way to solve a problem. Instructor Resources The following supplemental materials are available when this book is used in a classroom setting. All of the instructor resources available with this book are provided to the instructor on a single CD-ROM. ELECTRONIC INSTRUCTOR’S MANUAL. The Instructor’s Manual that accompanies this textbook includes additional instructional material to assist in class preparation, including items such as Sample Syllabi, Chapter Outlines, Technical Notes, Lecture Notes, Quick Quizzes, Teaching Tips, Discussion Topics, and Additional Case Projects EXAMVIEW ® . This textbook is accompanied by ExamView, a pow- erful testing software package that allows instructors to create and administer printed, computer (LAN-based), and Internet exams. ExamView includes hundreds of questions that correspond to the topics covered in this text, enabling students to generate detailed study guides that include page references for further review. The computer-based and Internet testing components allow students to take exams at their computers, and also save the instructor time by grading each exam automatically. POWERPOINT ® PRESENTATIONS. This book comes with Microsoft PowerPoint slides for each chapter. These are included as a teaching aid for classroom presentation, to make available to students xxi P R E FA C E on the network for chapter review, or to be printed for classroom distribution. Instructors can add their own slides for additional topics they introduce to the class. DATA FILES. Files that contain all of the data necessary for the xxii Hands-on Projects and Case Projects are provided through the Course Technology Web site at www.cengage.com/coursetechnology, and are also available on the Instructor Resources CD-ROM. SOLUTION FILES. Solutions to end-of-chapter Exercises and Projects are provided on the Instructor Resources CD and may also be found on the Course Technology Web site at www.cengage.com/ coursetechnology. The solutions are password protected. DISTANCE LEARNING. Course Technology is proud to present online test banks in WebCT and Blackboard to provide the most complete and dynamic learning experience possible. Instructors are encouraged to make the most of the course, both online and offline. For more information on how to access your online test bank, contact your local Course Technology sales representative. Read This Before You Begin The following information will help you as you prepare to use this textbook. To the User of the Data Files To complete the steps, exercises, and projects in this book, you will need data files that have been created specifically for this book. These data files are available through the Course Technology Web site at www.cengage.com/coursetechnology and are also provided on the Instructor Resources CD-ROM. Note that you can use a computer in your school lab or your own computer to complete the steps, exercises, and projects in this book. Using Your Own Computer You can use a computer in your school lab or your own computer to complete the chapters. To use your own computer, you will need the following: • A Web browser. You can use any browser you like to view the solutions to this exercises in this text, as long as it is compatible with the standardized version of the DOM that is recommended by the World Wide Web Consortium (W3C). At the time of this writing, Firefox and Internet Explorer 5.0 and higher are compatible with the W3C DOM, although other browsers are also compatible. • A code-based HTML editor, such as Adobe Dreamweaver, or a text editor such as Notepad on Windows, GNU Emacs on UNIX/ Linux, or SimpleText on the Macintosh. • A Web server (for Chapter 12) such as Apache HTTP Server or Microsoft Internet Information Services and PHP. Appendix A contains detailed instructions on how to install a Web server and PHP. To the Instructor To complete all the exercises and chapters in this book, your students must work with a set of user files, called data files, and download software from Web sites. The data files are included on the Instructor Resources CD-ROM. They may also be obtained electronically through the Course Technology Web site at www.cengage.com/ coursetechnology. Have students follow the instructions in Chapter 1 to install the data files. Course Technology Data Files You are granted a license to copy the data files to any computer or computer network used by individuals who have purchased this book. Visit Our World Wide Web Site Additional materials designed especially for this book might be available for your course. Periodically search www.cengage.com/coursetechnology for more information and materials to accompany this text. Got a Job In Computing . . . ? We hope you enjoyed the Q&A on the inside front cover of this book. If you’d like to suggest that we interview a recent graduate you know who has landed an interesting job in computing, please send your suggestions via e-mail to Amy Jollymore, Acquisitions Editor, at Amy.Jollymore@cengage.com. xxiii P R E FA C E Acknowledgements xxiv A text such as this represents the hard work of many people, not just the author. I would like to thank all the people who helped make this book a reality. First and foremost, I would like to thank Ann Shaffer, Development Editor; Alyssa Pratt, Senior Product Manager; and Amy Jollymore, Acquisitions Editor, for helping me get the job done. I would also like to thank Jill Braiewa, Senior Content Project Manager, and Tintu Thomas, Project Manager, who oversaw the process of turning the manuscript into a printed book. Also, many thanks to Chris Scriver, John Freitas, Serge Palladino, and Danielle Shaw, our excellent Quality Assurance team, who scrutinized every word and line of code. Many, many thanks to the reviewers who provided plenty of comments and positive direction during the development of this book: The following proposal reviewers helped me shape my plans for the new edition: Don Bergman, Olympic College; John Hulsey, Limestone College; Diane Kokoska, University of Maine at Augusta; William Kuechler, Jr., University of Nevada, Reno. The following people reviewed each and every chapter, providing countless helpful suggestions and comments: Ahmad Abuhejleh, University of Wisconsin— River Falls; Dan Luttrell, Community Colleges of Baltimore County, Catonsville Campus; Judy Scholl, Austin Community College; and Brian Snow, Central Maine Community College. A very special thanks to Judy Scholl, Austin Community College, for her invaluable advice on Chapter 12, “Updating Web Pages with AJAX.” On the personal side, I would like to thank my family and friends for supporting me in my career; I don’t see many of you nearly as often as I’d like, but you are always in my thoughts. My most important thanks always goes to my wonderful wife, Kathy, for her never ending support and encouragement, and to Noah the wonder dog. Don Gosselin CHAPTER Introduction to JavaScript In this chapter, you will:      Study the history of the World Wide Web Learn about Web development Add basic JavaScript code to your Web pages Learn about the JavaScript programming language Add structure to your JavaScript programs 1 CHAPTER 1 Introduction to JavaScript The original purpose of the World Wide Web (WWW) was to locate and display information. However, once the Web grew beyond a small academic and scientific community, people began to recognize that greater interactivity would make the Web more useful. As commercial applications of the Web grew, the demand for more interactive and visually appealing Web sites also grew. 2 To respond to the demand for greater interactivity, an entirely new Web programming language was needed. Netscape filled this need in the mid-1990s by developing the JavaScript programming language. Originally designed for use in the Navigator Web browser, JavaScript is now also used in most Web browsers, including Internet Explorer. Although JavaScript is considered a programming language, it is also a critical part of Web page design and authoring. This is because the JavaScript language “lives” within a Web page’s elements. In other words, the JavaScript code you write is usually placed within the elements that make up a Web page. JavaScript can turn static documents into applications such as games or calculators. JavaScript code can change the contents of a Web page after a browser has rendered it. It can also create visual effects such as animation, and it can control the Web browser window itself. None of this was possible before the creation of JavaScript. For the most current Web page-authoring techniques, see Don Gosselin’s XHTML, also published by Course Technology. In this chapter, you will learn the skills required to create basic JavaScript programs. In order to be successful in your JavaScript studies, you should already possess a strong knowledge of Web pageauthoring techniques. The first part of this chapter provides a quick refresher on the history of the World Wide Web and the basics on how to create Web pages. Even if you are highly experienced with HTML, you might not be familiar with the formal terminology that is used in Web page authoring. For this reason, be certain to read through these sections to ensure that you understand the terminology used in this book. Introduction to the World Wide Web The Internet is a vast network that connects computers all over the world. The original plans for the Internet grew out of a series of memos written by J. C. R. Licklider of the Massachusetts Institute of Technology (MIT), in August 1962, discussing his concept of a “Galactic Network.” Licklider envisioned a global computer network through which users could access data and programs from any site on the network. The Internet was actually developed in the 1960s by the Advanced Research Projects Agency (or ARPA) of the U.S. Department of Defense, which later changed its name to Defense Advanced Research Projects Agency (or DARPA). The goal of the Introduction to the World Wide Web early Internet was to connect the main computer systems of various universities and research institutions that were funded by this agency. This first implementation of the Internet was referred to as the ARPANET. More computers were connected to the ARPANET in the years following its initial development in the 1960s, although access to the ARPANET was still restricted by the U.S. government primarily to academic researchers, scientists, and the military. 3 The 1980s saw the widespread development of local area networks (LANs) and the personal computer. Although at one time restricted to academia and the military, computers and networks soon became common in business and everyday life. By the end of the 1980s, businesses and individual computer users began to recognize the global communications capabilities and potential of the Internet, and they convinced the U.S. government to allow commercial access to the Internet. In 1990 and 1991, Tim Berners-Lee created what would become the World Wide Web, or the Web, at the European Laboratory for Particle Physics (CERN) in Geneva, Switzerland, as a way to easily access cross-referenced documents that existed on the CERN computer network. When other academics and scientists saw the usefulness of being able to easily access cross-referenced documents using Berners-Lee’s system, the Web as we know it today was born. In fact, this method of accessing cross-referenced documents, known as hypertext linking, is probably the most important aspect of the Web because it allows you to open other Web pages quickly. A hypertext link, or hyperlink or link, contains a reference to a specific Web page that you can click to open that Web page. A common misconception is that the words “Web” and “Internet” are synonymous. The Web is only one part of the Internet and is a means of communicating on the Internet. The Internet is also composed of other communication elements such as e-mail systems that send and receive messages. However, because of its enormous influence on computing, communications, and the economy, the World Wide Web is arguably the most important part of the Internet today and is the primary focus of this book. A document on the Web is called a Web page and is identified by a unique address called the Uniform Resource Locator, or URL. A URL is also commonly referred to as a Web address. A URL is a type of Uniform Resource Identifier (URI), which is a generic term for many types of names and addresses on the World Wide Web. The term Web site refers to the location on the Internet of the Web pages and related files (such as graphic and video files) that belong to a company, organization, or individual. You display a Web page on your computer screen by using a program called a Web browser. A person can retrieve and open a Web page in a Web browser either by entering a If you want to learn more about the history of the Internet, the Internet Society (ISOC) maintains a list of links to Internet histories at http://www.isoc.org/ internet/ history/. CHAPTER 1 4 Prior to version 6, the Netscape Web browser was called Navigator or Netscape Navigator. With the release of version 6, however, Netscape dropped “Navigator” from the browser name, and now simply refers to its browser as “Netscape.” For this reason, in this book “Navigator Web browser” refers to versions older than version 6, and “Netscape Web browser” refers to version 6 and later. DHTML is actually a combination of HTML, Cascading Style Sheets, and JavaScript. The term Cascading Style Sheets (CSS), or style sheets, refers to a standard set by the W3C for managing Web page formatting. The W3C does not actually release a version of a particular technology. Instead, it issues a formal recommendation for a technology, which essentially means that the technology is (or will be) a recognized industry standard. Introduction to JavaScript URL in the Web browser’s Address box or by clicking a hypertext link. When a user wants to access a Web page, either by entering its URL in a browser’s Address box or by clicking a link, the user’s Web browser asks a Web server for the Web page in what is referred to as a request. A Web server is a computer that delivers Web pages. What the Web server returns to the user is called the response. Understanding Web Browsers You can choose from a number of different browsers, but at the time of this writing, Mozilla Firefox is the most popular browser on the market. Although Firefox is the most popular browser, it was not the first. NCSA Mosaic was created in 1993 at the University of Illinois and was the first program to allow users to navigate the Web by using a graphical user interface (GUI). In 1994, Netscape released Navigator, which soon controlled 75% of the market. Netscape maintained its control of the browser market until 1996, when Microsoft entered the market with the release of Internet Explorer, and the socalled browser wars began, in which Microsoft and Netscape fought for control of the browser market. The browser wars began over DHTML, which is a combination of various technologies, including HTML and JavaScript, which allows a Web page to change after it has been loaded by a browser. Examples of DHTML include the ability to position text and elements, change document background color, and create effects such as animation. Earlier versions of Internet Explorer and Navigator included DHTML elements that were incompatible. Furthermore, Microsoft and Netscape each wanted its version of DHTML to become the industry standard. To settle the argument, the World Wide Web Consortium set out to create a platform-independent and browser-neutral version of DHTML. The World Wide Web Consortium, or W3C, was established in 1994 at MIT to oversee the development of Web technology standards. While the W3C was drafting a recommendation for DHTML, versions 4 of Internet Explorer and Navigator each added a number of proprietary DHTML elements that were completely incompatible with the other browser. As a result, when working with advanced DHTML techniques such as animation, a programmer had to write a different set of HTML code for each browser. Unfortunately for Netscape, the W3C adopted as the formal standard the version of DHTML found in version 4 of Internet Explorer, which prompted many loyal Netscape followers to defect to Microsoft. One great benefit of the browser wars is that it has forced the Web industry to rapidly develop and adopt advanced Web page standards (including JavaScript, CSS, and DHTML), which are consistent across browsers. In 2004, Internet Explorer appeared to be winning the Introduction to the World Wide Web browser wars, as it controlled 95% of the browser market. Yet, in the past few years, Internet Explorer has lost significant market share to a contentious newcomer, Mozilla Firefox. The Firefox Web browser is open source software developed by the Mozilla organization (http:// www.mozilla.org). Open source refers to software for which the source code can be freely used and modified. At the time of this writing, Internet Explorer usage has slipped to approximately 41%, while Firefox now controls approximately 47% of the market (according to the W3 Schools browser statistics page at http://www.w3schools.com/browsers/ browsers_stats.asp). One of the most fascinating aspects of Firefox is that it’s essentially an open source version of the Netscape browser. So, in a figurative sense, the original Netscape browser has risen from the ashes to resume battle with its arch nemesis, Internet Explorer—and it’s winning at the time of this writing. Healthy competition is good for any market, so hopefully the renewed hostilities in the browser wars will encourage vendors to continue improving browser quality and capabilities, and to adopt and adhere to Web page standards. 5 Creating Web Pages Originally, people created Web pages using Hypertext Markup Language. Hypertext Markup Language, or HTML, is a markup language used to create the Web pages that appear on the World Wide Web. Web pages are also commonly referred to as HTML pages or documents. A markup language is a set of characters or symbols that defines a document’s logical structure—that is, it specifies how a document should be printed or displayed. HTML is based on an older language called Standard Generalized Markup Language, or SGML, which defines the data in a document independent of how the data will be displayed. In other words, SGML separates the data in a document from the way that data is formatted. Each element in an SGML document is marked according to its type, such as paragraphs, headings, and so on. Like SGML, HTML was originally designed as a way of defining the elements in a document independent of how they would appear. HTML was not intended to be used as a method of designing the actual appearance of the pages in a Web browser. However, HTML gradually evolved into a language that is capable of defining how elements should appear in a Web browser. Basic HTML Syntax HTML documents are text documents that contain formatting instructions, called tags, which determine how data is displayed on a Web page. HTML tags range from formatting commands that make text appear in boldface or italics to controls that allow user input, such as option buttons and check boxes. Other HTML tags allow you to display This textbook uses the terms Web pages and HTML documents interchangeably. CHAPTER 1 Introduction to JavaScript graphic images and other objects in a document or Web page. Tags are enclosed in brackets (< >), and most consist of an opening tag and a closing tag that surround the text or other items they format or control. The closing tag must include a forward slash ( / ) immediately after the opening bracket to define it as a closing tag. For example, to make a line of text appear in boldface, you use the opening tag and the closing tag . Any text contained between this pair of tags appears in boldface when you open the HTML document in a Web browser. 6 HTML documents must have a file extension of .htm or .html. A tag pair and any data it contains are referred to as an element. The information contained within an element’s opening and closing tags is referred to as its content. Some elements do not require a closing tag. Elements that do not require a closing tag are called empty elements because you cannot use a tag pair to enclose text or other elements. For instance, the element, which inserts a horizontal rule on a Web page, does not include a closing tag. You simply place the element anywhere in an HTML document where you want the horizontal rule to appear. There are literally hundreds of HTML elements. Table 1-1 lists some of the more common elements. HTML element Description Formats the enclosed text in a bold typeface Encloses the body of the HTML document Inserts a line break Centers a paragraph in the middle of a Web page Encloses the page header and contains information about the entire page Indicates heading level elements, where n represents a number from 1 to 6 Inserts a horizontal rule Begins and ends an HTML document; these are required elements Formats the enclosed text in an italic typeface Inserts an image file Identifies the enclosed text as a paragraph Formats the enclosed text as underlined Table 1-1 Common HTML elements All HTML documents must use the element as the root element. A root element contains all the other elements in a document. This element tells a Web browser to assemble any instructions between the tags into a Web page. The opening and closing Introduction to the World Wide Web . . . tags are required and contain all the text and other elements that make up the HTML document. Two other important HTML elements are the element and the element. The element contains information that is used by the Web browser, and you place it at the beginning of an HTML document, after the opening tag. You place several elements within the element to help manage a document’s content, including the element, which contains text that appears in a browser’s title bar. A element must contain a element. With the exception of the element, elements contained in the element do not affect the displaying of the HTML document. The element and the elements it contains are referred to as the document head. Following the document head is the element. The element and the text and elements it contains are referred to as the document body. When you open an HTML document in a Web browser, the document is assembled and formatted according to the instructions contained in its elements. The process by which a Web browser assembles and formats an HTML document is called parsing or rendering. The following example shows how to make a paragraph appear in boldface in an HTML document: Herbal treatments for migraines may help reduce the severity of pain and discomfort. HTML is not case sensitive, so you can use in place of . However, the next generation of HTML, a language called XHTML, is case sensitive, and you must use lowercase letters for elements. For this reason, this book uses lowercase letters for all elements. (You will learn about XHTML shortly.) You use various parameters, called attributes, to configure many HTML elements. You place an attribute before the closing bracket of the opening tag, and separate it from the tag name or other attributes with a space. You assign a value to an attribute using the syntax attribute="value". For example, you can configure the element, which embeds an image in an HTML document, with a number of attributes, including the src attribute. The src attribute specifies the filename of an image file or video clip. To include the src attribute within the element, you type . When a Web browser parses or renders an HTML document, it ignores nonprinting characters such as tabs and line breaks; the final document that appears in the Web browser includes only recognized HTML elements and text. You cannot use line breaks in the body of an HTML document to insert spaces before and after a paragraph; 7 CHAPTER 1 Introduction to JavaScript the browser recognizes only paragraph and line break elements for this purpose. In addition, most Web browsers ignore multiple, contiguous spaces on a Web page and replace them with a single space. The following code shows the document head and a portion of the document body for the Web page shown in Figure 1-1. 8 The Fitness Center Web page is available in your Examples folder for Chapter 1. The majority of the screen captures of Web pages shown in this book were taken in Mozilla Firefox 3, running on the Windows XP operating system. Different Web browsers might render the parts of a Web page slightly differently from other browsers. The appearance of a Web browser itself can also vary across platforms. If you are using a Web browser other than Firefox and an operating system other than Windows XP, your Web pages and Web browser might not match the figures in this book. X Fitness Center ... Figure 1-1 Fitness Center Web page Introduction to the World Wide Web Creating an HTML Document Because HTML documents are text files, you can create them in any text editor, such as Notepad or WordPad, or any word-processing application capable of creating simple text files. If you use a text editor to create an HTML document, you cannot view the final result until you open the document in a Web browser. Instead of a text editor or word processor, you could choose to use an HTML editor, which is an application designed specifically for creating HTML documents. Some popular HTML editors, such as Adobe Dreamweaver and Microsoft Expression Web, have graphical interfaces that allow you to create Web pages and immediately view the results, similar to the WYSIWYG (what-you-see-is-what-you-get) interface in wordprocessing programs. In addition, many current word-processing applications, including Microsoft Word and WordPerfect, allow you to save files as HTML documents. Like text editors, HTML editors create simple text files, but they automate the process of applying elements. For example, suppose you are creating a document in Word. You can add boldface to a heading in the document simply by clicking a toolbar button. Then, when you save the document as an HTML document, Word automatically adds the element to the text in the HTML document. Any HTML editor can greatly simplify the task of creating Web pages. However, HTML editors automatically add many unfamiliar elements and attributes to documents that might confuse you and distract from the learning process. For this reason, in this book you create Web pages using a simple text editor. Working with XHTML and Well-Formed Web Pages HTML first became an Internet standard in 1993 with the release of version 1.0. The next version of HTML, 2.0, was released in 1994 and included many core HTML features, such as forms and the ability to bold and italicize text. However, many of the standard features that are widely used today, such as using tables to organize text and graphics on a page, were not available until the release of HTML 3.2 in 1996. The current version of HTML, 4.01, was released in 1999. HTML 4.01, however, is the last version of the HTML language; it has been replaced with Extensible Hypertext Markup Language, or XHTML, which is the next generation markup language for creating the Web pages that appear on the World Wide Web. HTML has been replaced because it is useful only for rendering documents in traditional Web browsers like Firefox or Internet Explorer. 9 Many people who are new to creating Web pages are surprised by the fact that you cannot use a Web browser to create an HTML document. CHAPTER 1 Introduction to JavaScript XHTML is based on Extensible Markup Language, or XML, which is used for creating Web pages and for defining and transmitting data between applications. That worked well as long as browsers running on computers were the main source of requests for files over the Web. These days, however, many types of devices besides computers use the Web. For example, mobile phones and personal digital assistants (PDAs) are commonly used to browse the Web. An application that is capable of retrieving and processing HTML and XHTML documents is called a user agent. A user agent can be a traditional Web browser or a device such as a mobile phone or PDA, or even an application such as a crawler for a search engine that simply collects and processes data instead of displaying it. Although user agents other than browsers can process HTML, they are not ideally suited to the task, primarily because HTML is more concerned with how data appears than with the data itself. As Web browsers have evolved over the years, they have added extensions (elements and attributes) to HTML to provide functionality for displaying and formatting Web pages. For instance, one extension to the original HTML language is the element, which allows you to specify the font for data in an HTML document. The element has nothing to do with the type of data in an HTML document. Instead, its sole purpose is to display data in a specific typeface within a Web browser. There is nothing wrong with continuing to author your Web pages using HTML and design elements such as the element—provided that your Web pages will be opened only in a Web browser. However, many user agents (such as mobile phones and PDAs) are incapable of processing HTML elements that handle the displaying and formatting of data. User agents such as these require a language that truly defines data (such as a paragraph or heading) independently of the way it is displayed. To ensure backward compatibility with older browsers, you should save XHTML documents with an extension of .html or .htm, just like HTML documents. The Web page examples and exercises in this book are written in XHTML. Although you need to have a solid understanding of HTML to be successful with this book, you do not necessarily need to be an expert with XHTML. Because XHTML is almost identical to HTML, you can easily adapt any of your existing HTML skills to XHTML, and vice versa. If you are not familiar with XHTML, review Appendix C, “Working with Well-Formed Web Pages,” before continuing with this chapter. Be sure you understand what a document type definition, or DTD, is. Also, you should thoroughly understand how to create well-formed documents and how to work with CSS. 10 Now you are ready to start creating a Web page that displays the menu page for a pizza restaurant. You can use any text editor, such as Notepad or WordPad. Most of the Web page’s design comes from a style sheet that is already created for you in the DonsPizza folder in your Chapter folder for Chapter 1. Before you begin the first exercise, be certain to extract the data files, which you can download from Course Technology’s Web site at Introduction to the World Wide Web http://www.course.com. Use the 0538748877_Data.exe file to install the data files on Windows operating systems and the 0538748877_Data. jar file to install the data files on UNIX/Linux operating systems. The 0538748877_Data.exe and 0538748877_Data.jar files automatically create directories where you can store the exercises and projects you create in this book and install any necessary data files that you will need. By default, the directories and data files are installed for Windows platforms in C:\Course Technology\Programming\ JavaScript\Data Files and for UNIX/Linux platforms in usr/local/ course/programming/javascript/data_files. The data file directories contain separate directories for each chapter, which, in turn, contain the Chapter, Exercises, and Projects directories. The Course Technology directory might also contain data files for other books you have used from Course Technology. Save the exercises and projects you create in the main body of each chapter within the Chapter directory. Save the Hands-On Exercises and Discovery Projects you create at the end of each chapter in the Exercises and Projects directories, respectively. To create the menu page for Don’s Pizza: 1. Start your text editor and create a new document, if necessary. 2. Type the following declaration for the transitional DTD: 3. Add to the end of the document the following elements to begin the HTML document. Remember that all HTML documents must begin and end with the element. 4. Next, add the following and elements between the . . . tag pair. The title appears in your Web browser’s title bar. Remember that the element must include the element. The element cannot exist outside the element. The element links to a style sheet named style.css. Don's Pizza The arrow symbol at the end of a line of code indicates the code is broken in this book because of space limitations. But in your program, you must type the code on a single line. 11 CHAPTER 1 Introduction to JavaScript 5. Next, add the following elements above the closing tag. The element contains all of the elements that are rendered in a Web browser. 12 6. Add the following elements and text above the closing element. The code contains standard HTML ele- ments along with the text that is displayed in the Web browser. Some Web servers do not correctly interpret spaces within the name of HTML files. For example, some Web servers may not correctly interpret a filename of Mortgage Brokers.html, with a space between Mortgage and Brokers. For this reason, filenames in this book do not include spaces. [Add code here] © All rights reserved. Don's Pizza. 2010. 7. Save the document as menu.html in the DonsPizza folder in your Chapter folder for Chapter 1. Some text editors automatically add their own extensions to a document. Notepad, for instance, adds an extension of .txt by default. Be sure your document is saved with an extension of .html. Keep the document open in your text editor. Introduction to the World Wide Web 8. Open the menu.html document in your Web browser. (You open a local document in most Web browsers by selecting Open or Open File from the File menu.) Figure 1-2 displays the menu.html document as it appears in Firefox. 13 Many of the projects and examples in this book use professionally designed Web sites because, in real-world situations, a JavaScript programmer is often asked to add code to a preexisting Web site. However, do not worry about trying to understand the design elements that you see in this book. Instead, simply focus on how JavaScript interacts with the Web pages you work on. Figure 1-2 9. menu.html in Firefox Close your Web browser window. Short Quiz 1 1. How and why did the World Wide Web evolve? 2. What prompted the browser wars? 3. What are the basic elements required for all Web pages? 4. What is a user agent? CHAPTER 1 Introduction to JavaScript Introduction to Web Development 14 Another term that you might often see in relation to Web development is Webmaster. Although there is some dispute over exactly what the term means, typically Webmaster refers to a person who is responsible for the day-to-day maintenance of a Web site, including the monitoring of Web site traffic and ensuring that the Web site’s hardware and software are running properly. The duties of a Webmaster often require knowledge of Web page design, authoring, and development. If you would like to study the topic of Web page design itself, refer to Joel Sklar’s excellent book, Principles of Web Design, Fourth Edition, published by Course Technology/Cengage Learning. Web page design, or Web design, refers to the visual design and creation of the documents that appear on the World Wide Web. Most businesses today—both prominent and small—have Web sites. To attract and retain visitors, and to stand out from the crowd, Web sites must be exciting and visually stimulating. High-quality Web design plays an important role in attracting first-time and repeat visitors. However, the visual aspect of a Web site is only one part of the story. Equally important is the content of the Web site and how that content is structured. Web design is an extremely important topic. However, this book is not about Web design, even though you will certainly learn many Web design concepts and techniques as you work through the chapters ahead. Instead, this book touches on both Web page authoring and Web development. Web page authoring (or Web authoring) refers to the creation and assembly of the tags, attributes, and data that make up a Web page. There is a subtle, but important, distinction between Web design and Web page authoring: Web design refers to the visual and graphical design aspects of creating Web pages, whereas a book on Web page authoring refers to the physical task of assembling the Web page tags and attributes. Web development, or Web programming, refers to the design of software applications for a Web site. Generally, a Web developer works “behind the scenes” to develop software applications that access databases and file systems, communicate with other applications, and perform other advanced tasks. The programs created by a Web developer will not necessarily be seen by a visitor to a Web site, although the visitor will certainly use a Web developer’s programs, particularly if the Web site writes and reads data to and from a database. Although JavaScript lives more in the realm of Web page authoring, there is certainly some overlap between Web authoring and Web development, especially when it comes to sending and receiving data to and from a Web server. There are countless ways of combining the hundreds of HTML tags to create interesting Web pages. One technique that professional Web authors use to increase their HTML skill is examining the underlying HTML tags of a Web page that they admire. All Web browsers contain commands that allow you to view the underlying HTML code for a Web page that appears in the browser; in Firefox you select Page Source from the View menu, and in Internet Explorer you select the Source command from the View menu. The open nature of HTML makes it possible for anyone to easily see how another Web author created a Web page. However, you should Introduction to Web Development never copy another Web page author’s work and attempt to pass it off as your own. As a responsible member of the Web community, you should examine the HTML code behind a Web page only to improve your own skills. The potential theft of another Web page author’s hard work and intellectual property is no small concern. Not only is stealing another Web page author’s code and Web page designs unscrupulous, but in many cases it is illegal, especially if the work is copyrighted. Throughout this book, you will examine the underlying HTML code from various published Web sites. However, remember that your reasons for examining existing HTML code should be to understand the techniques used to create specific elements on a Web page in order to improve your own skills, not to hijack someone else’s hard work. Understanding Client/Server Architecture To be successful in Web development, you need to understand the basics of client/server architecture. There are many definitions of the terms client and server. In traditional client/server architecture, the server is usually some sort of database from which a client requests information. A server fulfills a request for information by managing the request or serving the requested information to the client—hence the term, client/server. A system consisting of a client and a server is known as a two-tier system. One of the primary roles of the client, or front end, in a two-tier system is the presentation of an interface to the user. The user interface gathers information from the user, submits it to a server, or back end, then receives, formats, and presents the results returned from the server. The main responsibility of a server is usually data storage and management. On client/server systems, heavy processing, such as calculations, usually takes place on the server. As desktop computers become increasingly powerful, however, many client/server systems have begun placing at least some of the processing responsibilities on the client. In a typical client/server system, a client computer might contain a front end that is used for requesting information from a database on a server. The server locates records that meet the client request, performs some sort of processing, such as calculations on the data, and then returns the information to the client. The client computer can also perform some processing, such as building the queries that are sent to the server or formatting and presenting the returned data. Figure 1-3 illustrates the design of a two-tier client/ server system. 15 CHAPTER 1 Introduction to JavaScript Client request Server response 16 Client Figure 1-3 Two-tier client/server architecture is a physical arrangement in which the client and server are two separate computers. Three-tier client/server architecture is more conceptual than physical, because the storage tier can be located on the same server. Multitier client/server architecture is also referred to as n-tier architecture. Server The design of a two-tier client/server system The Web is built on a two-tier client/server system, in which a Web browser (the client) requests documents from a Web server. The Web browser is the client user interface. You can think of the Web server as a repository for Web pages. After a Web server returns the requested document, the Web browser (as the client user interface) is responsible for formatting and presenting the document to the user. The requests and responses through which a Web browser and Web server communicate happen with HTTP. For example, if a Web browser requests the URL http://www.course.com, the request is made with HTTP because the URL includes the HTTP protocol. The Web server then returns to the Web browser an HTTP response containing the response header and the HTML (or XHTML) for Course Technology’s home page. After you start adding databases and other types of applications to a Web server, the client/server system evolves into what is known as a three-tier client architecture. A three-tier, or multitier, client/server system consists of three distinct pieces: the client tier, the processing tier, and the data storage tier. The client tier, or user interface tier, is still the Web browser. However, the database portion of the two-tier client/server system is split into a processing tier and the data storage tier. The processing tier, or middle tier, handles the interaction between the Web browser client and the data storage tier. (The processing tier is also sometimes called the processing bridge.) Essentially, the client tier makes a request of a database on a Web server. The processing tier performs any necessary processing or calculations based on the request from the client tier, and then reads information from or writes information to the data storage tier. The processing tier also handles the return of any information to the client tier. Note that the processing tier is not the only place where processing can occur. The Web browser (client tier) still renders Web page documents (which requires processing), and the database or application in the data storage tier might also perform some processing. Figure 1-4 illustrates the design of a three-tier client/server system. Introduction to Web Development Processing tier Client tier Data storage tier 17 Handles user interface display (the Web browser) and submits requests to the processing tier Handles interaction between the Web browser client and the data storage tier Stores data in a database and returns requests presented by the processing tier Can be the same computer Figure 1-4 The design of a three-tier client/server system JavaScript and Client-Side Scripting As mentioned earlier, HTML was not originally intended to control the appearance of pages in a Web browser. When HTML was first developed, Web pages were static—that is, they couldn’t change after the browser rendered them. However, after the Web grew beyond a small academic and scientific community, people began to recognize that greater interactivity and better visual design would make the Web more useful. As commercial applications of the Web grew, the demand for more interactive and visually appealing Web sites also grew. HTML and XHTML could only be used to produce static documents. You can think of a static Web page written in HTML or XHTML as being approximately equivalent to a document created in a wordprocessing or desktop publishing program; the only thing you can do with it is view it or print it. Thus, to respond to the demand for greater interactivity, an entirely new Web programming language was needed. Netscape filled this need by developing JavaScript. JavaScript is a client-side scripting language that allows Web page authors to develop interactive Web pages and sites. Client-side scripting refers to a scripting language that runs on a local browser (on the client tier) instead of on a Web server (on the processing tier). Originally designed for use in Navigator Web browsers, JavaScript is now also used in most other Web browsers, including Firefox and Internet Explorer. The term scripting language is a general term that originally referred to fairly simple programming languages that did not contain the CHAPTER 1 18 Many people think that JavaScript is related to or is a simplified version of the Java programming language. However, the languages are entirely different. Java is an advanced programming language that was created by Sun Microsystems and is considerably more difficult to master than JavaScript. Although Java can be used to create programs that can run from a Web page, Java programs are usually external programs that execute independently of a browser. In contrast, JavaScript programs always run within a Web page and control the browser. Introduction to JavaScript advanced programming capabilities of languages such as Java or C++. When it comes to Web development, the term scripting language refers to any type of language that is capable of programmatically controlling a Web page or returning some sort of response to a Web browser. It’s important to note that, although the term scripting language originally referred to simple programming languages, today’s Web-based scripting languages are anything but simple. The part of a browser that executes scripting language code is called the browser’s scripting engine. A scripting engine is just one kind of interpreter, with the term interpreter referring generally to any program that executes scripting language code. When a scripting engine loads a Web page, it interprets any programs written in scripting languages, such as JavaScript. A Web browser that contains a scripting engine is called a scripting host. Firefox and Internet Explorer are examples of scripting hosts that can run JavaScript programs. JavaScript was first introduced in Navigator and was originally called LiveScript. With the release of Navigator 2.0, the name was changed to JavaScript 1.0. Subsequently, Microsoft released its own version of JavaScript in Internet Explorer 4.0 and named it JScript. When Microsoft released JScript, several major problems occurred. First, the Netscape and Microsoft versions of the JavaScript language differed so greatly that programmers were required to write almost completely different JavaScript programs for Navigator and Internet Explorer. To avoid similar problems in the future, an international, standardized version of JavaScript, called ECMAScript, was created. The most recent version of ECMAScript is edition 3. Both Netscape JavaScript and Microsoft JScript conform to ECMAScript edition 3. Nevertheless, Netscape JavaScript and Microsoft JScript each include unique programming features that are not supported by the other language. In this book, you will learn to create JavaScript programs with ECMAScript edition 3, which is supported by all current Web browsers including Firefox, Netscape 6 and higher, and Internet Explorer 4 and higher. Although JavaScript is considered a programming language, it is also a critical part of Web page authoring. This is because the JavaScript language “lives” within a Web page’s elements. JavaScript gives you the ability to: • Turn static Web pages into applications such as games or calculators. • Change the contents of a Web page after a browser has rendered it. • Create visual effects such as animation. • Control the Web browser window itself. Introduction to Web Development For security reasons, the JavaScript programming language cannot be used outside of the Web browser. For example, to prevent mischievous scripts from stealing information, such as your e-mail address or credit card information you use for an online transaction, or from causing damage by changing or deleting files, JavaScript does not allow any file manipulation whatsoever. Similarly, JavaScript does not include any sort of mechanism for creating a network connection or accessing a database. This limitation prevents JavaScript programs from infiltrating a private network or intranet from which information might be stolen or damaged. Another helpful limitation is the fact that JavaScript cannot run system commands or execute programs on a client. The ability to read and write cookies is the only type of access to a client that JavaScript has. Web browsers, however, strictly govern cookies and do not allow access to cookies from outside the domain that created them. This security also means that you cannot use JavaScript to interact directly with Web servers that operate at the processing tier. Although the programmer can employ a few tricks (such as forms and query strings) to allow JavaScript to interact indirectly with a Web server, if you want true control over what’s happening on the server, you need to use a server-side scripting language, as explained in the next section. Understanding Server-Side Scripting Server-side scripting refers to a scripting language that is executed from a Web server. Some of the more popular server-side scripting languages are PHP, Active Server Pages (ASP), and Java Server Pages (JSP). One of the primary reasons for using a server-side scripting language is to develop interactive Web sites that communicate with a database. Server-side scripting languages work in the processing tier and have the ability to handle communication between the client tier and the data storage tier. At the processing tier, a server-side scripting language usually prepares and processes the data in some way before submitting it to the data storage tier. Some of the more common uses of server-side scripting language that you have probably already seen on the Web include the following: • Shopping carts • Search engines • Mailing lists and message boards • Web-based e-mail systems • Authentication and security mechanisms • Web logs (blogs) • Games and entertainment 19 CHAPTER 1 20 Introduction to JavaScript Unlike JavaScript, a server-side scripting language can’t access or manipulate a Web browser. In fact, a server-side scripting language cannot run on a client tier at all. Instead, a server-side scripting language exists and executes solely on a Web server, where it performs various types of processing or accesses databases. When a client requests a server-side script, the script is interpreted and executed by the scripting engine within the Web server software. After the script finishes executing, the Web server software translates the results of the script (such as the result of a calculation or the records returned from a database) into HTML or XHTML, which it then returns to the client. In other words, a client will never see the server-side script, only the HTML or XHTML that the Web server software returns from the script. Figure 1-5 illustrates how a Web server processes a server-side script. Client requests a PHP script The scripting engine within the Web server interprets and executes the server-side scripting code and translates the results into HTML or XHTML Web server returns HTML or XHTML Web browser Figure 1-5 Web server Web server sofware How a Web server processes a server-side script Should You Use Client-Side or Server-Side Scripting? An important question in the design of any client/server system is deciding how much processing to place on the client and how much to place on the server. In the context of Web site development, you must decide whether to use client-side JavaScript or a server-side script. This is an important consideration because the choice you make can greatly affect the performance of your program. In some cases, the decision is simple. For example, if you want to control the Web browser, you must use JavaScript. If you want to access a database on a Web server, you must use a server-side script. However, there are tasks that both languages can accomplish, such as validating forms and manipulating cookies. Furthermore, both languages can perform the same types of calculations and data processing. A general rule of thumb is to allow the client to handle the user interface processing and light processing, such as data validation, but have the Web server perform intensive calculations and data storage. This division of labor is especially important when dealing with clients and servers over the Web. Unlike with clients on a private network, it’s Introduction to Web Development not possible to know in advance the computing capabilities of each client on the Web. You cannot assume that each client (browser) that accesses your client/server application (Web site) has the necessary power to perform the processing required by the application. For this reason, intensive processing should be performed on the server. Because servers are usually much more powerful than client computers, your first instinct might be to let the server handle all processing and only use the client to display a user interface. Although you do not want to overwhelm clients with processing they cannot handle, it is important to perform as much processing as possible on the client for several reasons: • Distributing processing among multiple clients creates applications that are more powerful, because the processing power is not limited to the capabilities of a single computer. Client computers become more powerful every day, and advanced capabilities such as JavaScript are now available in local Web browsers. Thus, it makes sense to use a Web application to harness some of this power and capability. A Web application is a program that executes on a server but that clients access through a Web page loaded in a browser. • Local processing on client computers minimizes transfer times across the Internet and creates faster applications. If a client had to wait for all processing to be performed on the server, a Web application could be painfully slow over a busy Internet connection. • Performing processing on client computers lightens the processing load on the server. If all processing in a three-tier client/server system is done on the server, the server for a popular Web site could become overwhelmed trying to process requests from numerous clients. Short Quiz 2 1. What are the differences among Web page design, Web page authoring, and Web development? 2. What are the primary roles of the client and the server in two-tier system architecture? 3. What is the purpose of the processing tier in three-tier system architecture? 4. Why are scripts written with the JavaScript programming language restricted to executing only within a Web browser? 21 CHAPTER 1 Introduction to JavaScript Adding JavaScript to Your Web Pages The following sections introduce basic procedures for adding JavaScript to your Web pages. 22 Using the Element JavaScript programs run from within a Web page (either an HTML or XHTML document). That is, you type the code directly into the Web page code as a separate section. JavaScript programs contained within a Web page are often referred to as scripts. The element tells the Web browser that the scripting engine must interpret the commands it contains. The type attribute of the element tells the browser which scripting language and which version of the scripting language is being used. You assign a value of “text/javascript” to the type attribute to indicate that the script is written with JavaScript. You need to include the following code in a document to tell the Web browser that the statements that follow must be interpreted by the JavaScript scripting engine: statements Next, you will add a script section to the Menu page for Don’s Pizza. To add a script section to the Menu page for the pizza restaurant: 1. Return to the menu.html document in your text editor. 2. Replace the [Add code here] line with the following script section: 3. Save the menu.html document. The individual lines of code, or statements, that make up a JavaScript program in a document are contained within the element. The following script contains a single statement that writes the text “Can you hear me now?” to a Web browser window, using the write() method of the Document object, which you will study shortly: document.write("Can you hear me now?"); Notice that the preceding statement ends in a semicolon. Many programming languages, including C++ and Java, require you to end all statements with a semicolon. JavaScript statements are not required to end in semicolons. Semicolons are strictly necessary only when you want to separate statements that are placed on a single line. Adding JavaScript to Your Web Pages For example, the following script contains two statements on the same line, with each statement ending in a semicolon: document.write("Can you "); document.write ("hear me now?"); As long you place each statement on its own line, separated from other lines with line breaks, you are not required to end statements with semicolons. The following code shows another example of the preceding script, but this time, each statement is placed on its own line, without an ending semicolon. document.write("Can you ") document.write("hear me now?") Even though the statements do not end in semicolons, the preceding script is legal. However, that’s not the end of the story. Programmers often adopt conventions in their code that make the code easier for the programmer to read in a text editor. In the case of semicolons, it is considered good JavaScript programming practice to end any statement with a semicolon. The semicolon serves to identify the end of each statement, making it easier for the programmer to read his or her own code (and for other programmers to read the code later on). Therefore, be sure to end all of your JavaScript statements with semicolons. Understanding JavaScript Objects Before you can use elements to create a JavaScript program, you need to learn some basic terminology that is commonly used in JavaScript programming and in other kinds of programming languages. In addition to being an interpreted scripting language, JavaScript is considered an object-based programming language. An object is programming code and data that can be treated as an individual unit or component. For example, you might create a CarLoan object that calculates the number of payments required to pay off a car loan....
Purchase answer to see full attachment
User generated content is uploaded by users for the purposes of learning and should be used following Studypool's honor code & terms of service.

Explanation & Answer


Anonymous
Really great stuff, couldn't ask for more.

Studypool
4.7
Trustpilot
4.5
Sitejabber
4.4

Related Tags