javascript and ajax - harvard...

25
Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout... 1 of 49 4/1/2008 1:48 PM Table of Contents | All Slides | Link List | Examples | CSCI E-12 Javascript March 19, 2008 Harvard University Division of Continuing Education Extension School Course Web Site: http://cscie12.dce.harvard.edu/ Copyright 1998-2008 David P. Heitmeyer Instructor email: [email protected] Course staff email: [email protected] Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout... 2 of 49 4/1/2008 1:48 PM Parameters sent to Server-side Processes Server-side Process (the Program) Expecting certain parameters Parameters alter/configure behavior Form Elements Provide interface to fill-out and submit expected parameters. Javascript can provide functionality to validate form fields before submission

Upload: phungphuc

Post on 26-Mar-2018

219 views

Category:

Documents


1 download

TRANSCRIPT

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

1 of 49 4/1/2008 1:48 PM

Table of Contents | All Slides | Link List | Examples | CSCI E-12

JavascriptMarch 19, 2008

Harvard University Division of Continuing Education

Extension School

Course Web Site: http://cscie12.dce.harvard.edu/

Copyright 1998-2008 David P. Heitmeyer

Instructor email: [email protected] Course staff email: [email protected]

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

2 of 49 4/1/2008 1:48 PM

Parameters sent to Server-side Processes

Server-side Process (the Program)Expecting certain parametersParameters alter/configure behavior

Form ElementsProvide interface to fill-out and submit expected parameters.Javascript can provide functionality to validate form fields before submission

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

3 of 49 4/1/2008 1:48 PM

Weather by Zip Code from Weather.com

InputThe URL where the form information is sent is specified by the action parameter:action="http://www.weather.com/search/search"

The parameter that the server-side process is expecting is where and the value of thisparameter is the zip code.

OutputHTML page showing the weather

Can supply the where parameter in the query string of an href parameter:

Example 8.1

Example 8.1 Source:

Example 8.1 Rendered:

Weather from weather.com:

Cambridge, MACoronado, CADallas, TXChicago, IL

Can build a form where the user inputs zip code:

Example 8.2

Example 8.2 Source:

Example 8.2 Rendered:

Input zip code:

view plain print ?

<div>Weather from <a href="http://www.weather.com" shape="rect" >weather.com</a>:</div> 1.<ul> 2. <li><a href="http://www.weather.com/search/search?where=02138" shape="rect" >Cambridge,3. </li> 4. <li><a href="http://www.weather.com/search/search?where=92118" shape="rect" >Coronado, 5. </li> 6. <li><a href="http://www.weather.com/search/search?where=75201" shape="rect" >Dallas, TX7. </li> 8. <li><a href="http://www.weather.com/search/search?where=60601" shape="rect" >Chicago, I9. </li> 10.</ul> 11.

view plain print ?

<form method="get" action="http://www.weather.com/search/search" enctype="application/x-1. <div> Input zip code: 2. <input type="text" name="where" /> 3. <br/> 4. <input type="submit" name="submit" value="Get Forecast" /> </div> 5.</form> 6.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

4 of 49 4/1/2008 1:48 PM

Get Forecast

Supply the wrong parameter name or value type

In this example, we send a value that is not a zip code where=ABCDEFGHIJKLMNOPQRSTUVWXYZ. What willhappen?

Example 8.3

Example 8.3 Source:

Example 8.3 Rendered:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

In this example, we send a correct zip code, but use the parameter name of zipcode instead of where. What will happen?

Example 8.4

Example 8.4 Source:

Example 8.4 Rendered:

Cambridge, MA

view plain print ?

<ul> 1. <li><a href="http://www.weather.com/search/search?where=ABCDEFGHIJKLMNOPQRSTUVWXYZ" sha2. </li> 3.ul> 4.

view plain print ?

<ul> 1. <li><a href="http://www.weather.com/search/search?zipcode=02138" shape="rect" >Cambri2. MA</a> 3. </li> 4.</ul> 5. 6.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

5 of 49 4/1/2008 1:48 PM

Server-side programs or Services we can use

RedirectSearchMapsData Collection

EmailDatabase

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

6 of 49 4/1/2008 1:48 PM

Redirect

actionhttp://minerva.dce.harvard.edu/cgi-bin/redirect.cgi

parametersURL

The following form uses the parameter: URL

Example 8.5

Example 8.5 Source:

Example 8.5 Rendered:

Select your destination:Select your destination: Go!

view plain print ?

<form method="post" action="http://minerva.dce.harvard.edu/cgi-bin/redirect.cgi" enctype1. <div> 2. <select name="URL" > 3. <option value="" >Select your destination:</option> 4. <option value="http://www.w3.org/TR/xhtml1" >XHTML 1.0</option> 5. <option value="http://www.w3.org/TR/html401" >HTML 4.01</option> 6. <option value="http://www.w3.org/TR/CSS21" >CSS 2.1</option> 7. <option value="http://www.w3.org/TR/REC-CSS2" >CSS 2</option> 8. <option value="http://www.w3.org/TR/REC-CSS1" >CSS 1</option> 9. <option value="http://www.w3.org/WAI" >Web Accessibility Initiative 10. (WAI)</option> 11. <option value="http://validator.w3.org/" >XHTML/HTML Validator</option> 12. <option value="http://jigsaw.w3.org/css-validator/validator-uri.html" > CSS 13. Validator</option> 14. </select> 15. <input type="submit" value="Go!" /> 16. </div> 17.</form> 18.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

7 of 49 4/1/2008 1:48 PM

Mail

FormMail Documentation. Note that this script can be used to send email only to addresses endingwith .harvard.edu

actionhttp://minerva.dce.harvard.edu/cgi-bin/FormMail

parametersrecipientsubjectemailredirectrequiredsortenv_reportprint_configprint_blank_fields...see documentation for complete list

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

8 of 49 4/1/2008 1:48 PM

Mail Form

Example 8.6

Example 8.6 Source:

Example 8.6 Rendered:

Your Email Address: Your Name: Subject: Lecture QuestionLecture Question

Message:

view plain print ?

<form action="http://minerva.dce.harvard.edu/cgi-bin/FormMail" method="get" enctype="app1. <div>Your Email Address: 2. <input type="text" name="email" /></div> 3. <div>Your Name: 4. <input type="text" name="realname" /></div> 5. <div>Subject: 6. <select name="subject" > 7. <option value="Lecture Question" >Lecture Question</option> 8. <option value="Assignment Question" >Assignment Question</option> 9. <option value="Syllabus Question" >Syllabus Question</option> 10. <option value="Website Question" >Website Question</option> 11. </select> </div> 12. <div>Message: 13. <br/> 14. <textarea rows="10" cols="60" name="message" >Please type message here... 15. </textarea> </div> 16. <div> 17. <input type="hidden" name="recipient" value="[email protected]" /> 18. </div> 19. <div> 20. <input type="submit" value="Send Email" /> 21. </div> 22.</form> 23.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

9 of 49 4/1/2008 1:48 PM

Send Email

Please type message here...

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

10 of 49 4/1/2008 1:48 PM

Mail Form

Example 8.7

Example 8.7 Source:

Example 8.7 Rendered:

Your Email Address: Your Name: What ice cream do you like?

Chocolate Vanilla Strawberry

Send Email

view plain print ?

<form action="http://minerva.dce.harvard.edu/cgi-bin/FormMail" method="get" enctype="app1. <div>Your Email Address: 2. <input type="text" name="email" /></div> 3. <div>Your Name: 4. <input type="text" name="realname" /></div> 5. <div> 6. <input type="hidden" name="subject" value="Favorite Ice Cream" /> What ice 7. cream do you like? 8. <br/> 9. <input type="checkbox" name="icecream" value="chocolate" />Chocolate 10. <br/> 11. <input type="checkbox" name="icecream" value="vanilla" />Vanilla 12. <br/> 13. <input type="checkbox" name="icecream" value="strawberry" />Strawberry 14. <br/> 15. <input type="hidden" name="recipient" value="[email protected]" /> 16. <input type="hidden" name="redirect" value="http://www.herrells.com/" /> 17. <input type="hidden" name="required" value="icecream,realname" /> </div> 18. <div> 19. <input type="submit" value="Send Email" /> 20. </div> 21.</form> 22.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

11 of 49 4/1/2008 1:48 PM

Form Data to a Database

FAS IT offers a Data Collection Toolthat allows you to send data submitted via an HTML form to a database. The data can be viewedonline (in HTML) or downloaded in an Excel file. Note that a Harvard HUID and PIN are required touse this tool.

Example 8.8

Example 8.8 Source:

Example 8.8 Rendered:

What ice cream do you like? Chocolate Herrell's Chocolate Pudding Chocolate Peanut Butter Vanilla Strawberry

Submit Query

view plain print ?

<form method="post" action="https://www.datacollection.fas.harvard.edu/cgi-bin/form2db.cg1. <div> 2. <input type="hidden" name="form2db" value="cscie12_test" /> 3. <!-- Your form elements go here --> 4. What ice cream do you like? 5. <br/> 6. <input type="checkbox" name="icecream" id="ic_chocolate" value="chocolate" /> 7. <label for="ic_chocolate" >Chocolate</label> 8. <br/> 9. <input type="checkbox" name="icecream" id="ic_hcp" value="herrell's chocolate puddi10. <label for="ic_hcp" >Herrell's Chocolate Pudding</label> 11. <br/> 12. <input type="checkbox" name="icecream" id="ic_cpb" value="chocolate peanut butter"13. <label for="ic_cpb" >Chocolate Peanut Butter</label> 14. <br/> 15. <input type="checkbox" name="icecream" id="ic_vanilla" value="vanilla" /> 16. <label for="ic_vanilla" >Vanilla</label> 17. <br/> 18. <input type="checkbox" name="icecream" id="ic_strawberry" value="strawberry" /> 19. <label for="ic_strawberry" >Strawberry</label> 20. <br/> 21. <input type="submit" /> </div> 22.</form> 23.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

12 of 49 4/1/2008 1:48 PM

Search

Example 8.9

Example 8.9 Source:

Example 8.9 Rendered:

Search CSCIE-12 with Google

view plain print ?

<form method="get" action="http://www.google.com/search" enctype="application/x-www-form1. <div> 2. <input type="text" name="as_q" size="50" /> 3. <br/> 4. <input type="submit" value="Search CSCIE-12 with Google" /> 5. <input type="hidden" name="as_sitesearch" value="cscie12.dce.harvard.edu" /> 6. </div> 7.</form> 8.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

13 of 49 4/1/2008 1:48 PM

Maps

http://maps.yahoo.com/

Example 8.10

Example 8.10 Source:

Example 8.10 Rendered:

1 Oxford St, Cambridge, MA 02138

q11 Oxford St, Cambridge, MA 02138

view plain print ?

<a href="http://maps.yahoo.com/maps_result?q1=1+Oxford+St,+Cambridge,+MA+02138&mag=5&ard=11. 1 Oxford St, Cambridge, MA 02138 </a> 2. 3.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

14 of 49 4/1/2008 1:48 PM

JavaScript

Wikipedia entries:

JavaScriptECMAScript

JavaScript is a scripting language most often used for client-side web development. It was the originating dialect of the ECMAScript standard. It is a dynamic, weakly typed, prototype-basedlanguage with first-class functions. JavaScript was influenced by many languages and was designedto have a similar look to Java, but be easier for non-programmers to work with. The language is bestknown for its use in websites (as client-side JavaScript), but is also used to enable scripting accessto objects embedded in other applications (for example Microsoft Gadgets in Windows VistaSidebar).

Client-side Triad

Structure - XHTML

Style (Presentation) - CSS

Function (Behavior) - JavaScript

JavaScript provides programmatic access to virtually all aspects of a page.

CSS propertiesMarkup contentForms, communication to Server

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

15 of 49 4/1/2008 1:48 PM

JS: Manipulate the Page

JS can be used to manipulate CSS properties.

Note the use of event attributes (onclick, onmouseover, onmouseout) as well as a javascript:protocol in an href value.

Example 8.11

Example 8.11 Source:

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

16 of 49 4/1/2008 1:48 PM

In example11.js

view plain print ?

<div id="cscie12-course" style="float: left; width: 50%; padding: 10px; margin: 10px; bor1. <h3>Fundamentals of Website Development</h3> 2. <p> Harvard Extension School, Spring 2007-2008 3. <br/> CSCI E-12 4. <br/> Wednesday, 5:30 to 7:30 pm</p> 5. <p id="cscie12-description" >This course provides a foundation in several facets of 6. establishing and maintaining a website. The first part of the course is devoted to 7. creating, designing, and publishing content on the Web (XHTML, HTML, CSS, JavaScript, 8. GIF, JPEG, PNG, and PDF). The second part of the course covers configuring and maintai9. a web server, including HTTP, access control, and security. Dynamically generated 10. websites and database-driven websites are discussed (CGI, PHP, and JSP). In addition, 11. tools and techniques for maintaining a website, such as log analysis, version control,12. document validation, and page and site analysis, are covered. Prerequisites: CSCI E-1,13. or the equivalent experience.</p> 14.</div> 15.<div style="width: 20%; float: left; margin-left: 2em;" > 16. <p><strong>Align Description</strong></p> 17. <ul> 18. <li><a href="#" onclick="align('right')" shape="rect" >right</a></li> 19. <li><a href="#" onclick="align('left')" shape="rect" >left</a></li> 20. <li><a href="#" onclick="align('justify')" shape="rect" >justify</a></li> 21. </ul> 22. <p><strong>Hide/Show/Toggle Description</strong></p> 23. <ul> 24. <li><a href="javascript:hidedesc()" shape="rect" >Hide</a></li> 25. <li><a href="#" onclick="showdesc()" shape="rect" >Show</a></li> 26. <li><a href="#" onclick="toggledesc()" shape="rect" >Toggle</a></li> 27. </ul> 28. <p><strong>Set background-color</strong></p> 29. <ul> 30. <li><a href="#" onclick="backgroundcolor('#f66')" shape="rect" >red</a></li> 31. <li><a href="#" onclick="backgroundcolor('#6f6')" shape="rect" >green</a></li> 32. <li><a href="#" onclick="backgroundcolor('#ff6')" shape="rect" >yellow</a></li> 33. <li><a href="#" onclick="backgroundcolor('#66f')" shape="rect" >blue</a></li> 34. <li><a href="#" onmouseover="backgroundcolor('#f6f')" onmouseout="revertcolor()"35. </ul> 36.</div> 37.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

17 of 49 4/1/2008 1:48 PM

In head element:

Example 8.11 Demonstrated

view plain print ?

function align(val) { 1. node = document.getElementById('cscie12-description'); 2. node.style.textAlign = val; 3.} 4.function hidedesc() { 5. node = document.getElementById('cscie12-description'); 6. node.style.display = 'none'; 7.} 8.function showdesc() { 9. node = document.getElementById('cscie12-description'); 10. node.style.display = 'block'; 11.} 12.function toggledesc() { 13. node = document.getElementById('cscie12-description'); 14. var currentdisplay = node.style.display; 15. if(currentdisplay == 'none') 16. showdesc(); 17. else 18. hidedesc(); 19.} 20.var previouscolor = '#fff'; 21.function backgroundcolor(color) { 22. node = document.getElementById('cscie12-course'); 23. previouscolor = node.style.backgroundColor; 24. node.style.backgroundColor = color; 25.} 26.function revertcolor() { 27. node = document.getElementById('cscie12-course'); 28. node.style.backgroundColor = previouscolor; 29.} 30.

view plain print ?

<script src="example11.js" type="text/javascript"> </script> 1.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

18 of 49 4/1/2008 1:48 PM

Exposing Additional Form Elements

Additional relevant form elements are exposed based upon user input. Here, this is achieved byhaving the entire form in the markup, with a certain section hidden via CSS (display: none;). If"Yes" is chosen, the display property is changed to "block" through JS.

Example 8.12

Example 8.12 Source:

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

19 of 49 4/1/2008 1:48 PM

In script element (within head element):

Example 8.12 Demonstrated

view plain print ?

<form method="get" action="http://minerva.dce.harvard.edu/cgi-bin/echo.cgi" name="ice_cr1. <div> Would you like ice cream?<br/> 2. <input type="radio" name="want" id="ic_yes" value="yes" onclick="displayIceCreamOp3. <label for="ic_yes" >Yes</label><br/> 4. <input type="radio" name="want" id="ic_no" value="no" onclick="displayIceCreamOpti5. <label for="ic_no" >No</label> </div> 6. 7. <div style="display: none; margin-left: 2em; background-color: #eee; padding: 1em; " id8. <fieldset> 9. <legend>Ice Cream Options</legend> 10. <p>How would you like it?</p> 11. <input type="radio" id="container_cup" name="container" value="cup" /> 12. <label for="container_cup" >Cup</label> 13. <br/> 14. <input type="radio" id="container_cone" name="container" value="cone" /> 15. <label for="container_cone" >Cone</label> 16. <br/> 17. <p>Pick your toppings:</p> 18. <input type="checkbox" name="toppings" id="toppings_wc" value="whipcream" /> 19. <label for="toppings_wc" >Whipped cream</label> 20. <br/> 21. <input type="checkbox" name="toppings" id="toppings_j" value="jimmies" /> 22. <label for="toppings_j" >Jimmies</label> 23. <br/> 24. <input type="checkbox" name="toppings" id="toppings_nuts" value="nuts" /> 25. <label for="toppings_nuts" >Nuts</label> 26. <br/> 27. <input type="checkbox" name="toppings" id="toppings_cherry" value="cherry" /> 28. <label for="toppings_cherry" >Cheery</label> 29. </fieldset> 30. </div> 31. <p><input type="submit" /></p> 32.</form> 33.

view plain print ?

function displayIceCreamOptions() { 1. var divico = document.getElementById('icecream_options'); 2. var state = divico.style.display; 3. if (document.forms['ice_cream'].want[0].checked) { 4. divico.style.display = 'block'; 5. } else { 6. divico.style.display = 'none'; 7. } 8.} 9.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

20 of 49 4/1/2008 1:48 PM

JavaScript and XHTML

Scripts in HTML Documents from the HTML 4 Specification http://www.w3.org/TR/html4/interact/scripts.html<script> element

<!ELEMENT script - - %Script; -- script statements --><!ATTLIST script charset %Charset; #IMPLIED -- char encoding of linked resource -- type %ContentType; #REQUIRED -- content type of script language -- src %URI; #IMPLIED -- URI for an external script -- defer (defer) #IMPLIED -- UA may defer execution of script -- >

<script> element typically goes in head, but can be a child of body and many other elements.Note the <noscript> element for clients without JavaScript.

To function in all browsers, scriptelement should not be empty, but should include a space, a comment, or even a simple return true; statement. Best:

<script src="jquery.js" type="text/javascript" > </script>

Don't use:

<script src="jquery.js" type="text/javascript" />

Event Attributes

These are attributes defined for X/HTML elements, which are "event attributes":

onbluronfocusonchangeonclickondblclickonkeydownonkeyuponkeypressonloadonunloadonmousedownonmousemoveonmouseoutonmouseoveronmouseuponresetonselectonsubmit

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

21 of 49 4/1/2008 1:48 PM

JavaScript in XHTML/HTML

External Script

Script within XHTML document

"Inline" scripts as values of event attributes

These generally should be avoided, but are useful to create JavaScript-based bookmarks,known as favelets (Google Search: favelets).

<script src="/url/to/javascript/file.js" type="text/javascript" > </script> 1.

<script type="text/javascript"> 1.

/* 2.

JavaScript code as content of script element 3. */ 4.

</script> 5.

<a href="#" 1.

onclick="javascript:void(window.resizeTo(800,600))"> 2.

Size Window to 800 x 600 3.

</a> 4.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

22 of 49 4/1/2008 1:48 PM

JS: Form Validation

Validate form input using the onsubmit event attribute.

Things to note:

onsubmit

false stops the form submissionthis is the magic object Validate function accepts an argument, which is the form objectOn failure, focus is put on failed input and background color changed.

Example 8.13

Example 8.13 Source:

In script element (within head element):

Example 8.13 Demonstrated

view plain print ?

<form onsubmit="return Validate(this)" method="get" action="http://minerva.dce.harvard.e1.<div> 2. <label for="YourName1" >Enter your name</label>: 3. <input type="text" id="YourName1" name="YourName" /> 4. <br/> 5. <input type="submit" value="Submit Information" /> 6.</div> 7.</form> 8.

view plain print ?

function Validate(thisForm) { 1. if(thisForm.YourName.value == null || thisForm.YourName.value == "") { 2. alert("Please enter your name!"); 3. thisForm.YourName.focus(); 4. thisForm.YourName.style.backgroundColor = '#ff9'; 5. return false; 6. } else { 7. return true; 8. } 9.} 10.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

23 of 49 4/1/2008 1:48 PM

Form Validation and Regular Expressions

Q. What if we want to test for a string pattern other than "null" or "empty"?... A. Regular Expressions!

Regular Expression for an email address: (yes, this is simplified)/^[\w\._-]+@[\w\._-]+\.[a-zA-Z]{2,7}$/

^beginning of the string

[\w\._-]+[square brackets] indicate a character class"\w" is a word character"+" means 1 or more times

@the "@" part of the email address

\.[a-zA-Z]{2,7}matches the TLD (dot something, where something is 2 to 7 letters

$end of string

Example 8.14

Example 8.14 Source:

In example14.js

view plain print ?

<form onsubmit="return Validate(this)" method="get" action="http://minerva.dce.harvard.e1. <div> 2. <label for="email1" >Email Address</label>: 3. <input type="text" size="32" name="email" id="email1" /> 4. <br/> 5. <input type="submit" /> </div> 6.</form> 7.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

24 of 49 4/1/2008 1:48 PM

In head element:

Example 8.14 Demonstrated

view plain print ?

// validates that the entry is formatted as an email address 1.function Validate(thisForm) { 2. var tocheck = thisForm.email.value; 3. var re = /^[\w\._-]+@[\w\._-]+\.[a-zA-Z]{2,7}$/; 4. if (!tocheck.match(re)) { 5. alert("Please verify the email address format."); 6. thisForm.email.focus(); 7. thisForm.email.style.backgroundColor = '#ff9'; 8. return false; 9. } else { 10. return true; 11. } 12.} 13.

view plain print ?

<script src="example14.js" type="text/javascript"> </script> 1.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

25 of 49 4/1/2008 1:48 PM

Your Work Easier with JavaScript Libraries

jQueryPrototype / ScriptaculousYahoo! UIDojo

jQuery

Although all of the libraries above are very good and each have their particular strenghts, we'll focusprimarily on jQuery. jQuery functionality is accessible regardless of background. Non-programmerscan employ its straightforward selection and syntax, while developers can take advantage of itsease-of-use to develop and even extend jQuery.

jQuery comes with "core" functionality. Additional functionality can be added through a variety ofcore and contributed plugins.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

26 of 49 4/1/2008 1:48 PM

jQuery: Table Striping

Let's get started with jQuery by "striping" a table. The plain table comes froma list of United StatesSenators.

Plain table:

Striped table:

Plain table: senate_table.htmlStriped table: senate_stripe.html Include some Javascript libraries (jquery.js and write a function that selects the table rows andapplies a class. Note that the jQuery selectors are like CSS selectors (and here we see customjQuery selectors of :even and :odd).

<script src="../js/jquery.js" type="text/javascript"> </script> 1. <script type="text/javascript"> 2.$(document).ready(function() { 3. $("table.senate tr:even").addClass('evenRow'); 4. $("table.senate tr:odd").addClass('oddRow'); 5.}); 6.</script> 7.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

27 of 49 4/1/2008 1:48 PM

Tables: Class gives Functionality

jQuery Tablesorter Plugin makes dealing with tables even easier!

Sortable table:

Tables are constructed with thead and tbody. Simply by giving them a class="sortable", the jQueryTablesorter Plugin makes them 'sortable' and 'striped':

Plain table: senate_table.htmlSortable table: senate_table_sortable.html Include some Javascript libraries (jquery.js and jquery.tablesorter.js), and give the table aclass.

The JavaScript and CSS:

Senate data comes from GovTrack.US. Table sorting is achieved through jQuery and thejQuery Tablesorter Plugin

<table class="tablesorter"> 1.

<script src="jquery-latest.js" type="text/javascript"> </script> 1. <script src="jquery.tablesorter.js" type="text/javascript"> </script> 2. <script type="text/javascript"> 3.$(document).ready( 4. function() { 5. $("table.sortable").tablesorter({widgets:['zebra']}) 6.}); 7.</script> 8. <link href="../js/blue/style.css" type="text/css" rel="stylesheet"/><style type="text/css9./* table styling */ 10..odd { background-color:#ddf; color: #000;} 11..even { background-color:#ff9; color: #000;} 12.</style> 13.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

28 of 49 4/1/2008 1:48 PM

Visual Effects with jQuery

Let's revisit part of an earlier example to see how we could do this in jQuery.

Items to note:

Separation. The "click" handler is bound via JavaScript and not the onclick atribute.

Fancier. jQuery provides many "effects" and "animations" (basic ones here are fadeOut and fadeIn)

Default Behavior Stopped. The default behavior for event propagation can be stopped.

Example 8.15

Example 8.15 Source:

view plain print ?

<div id="cscie12-course2" style="float: left; width: 50%; padding: 10px; margin: 10px; bo1. <h3>Fundamentals of Website Development</h3> 2. <p> Harvard Extension School, Spring 2007-2008 3. <br/> CSCI E-12 4. <br/> Wednesday, 5:30 to 7:30 pm</p> 5. <p id="cscie12-description2" >This course provides a foundation in several facets of 6. establishing and maintaining a website. The first part of the course is devoted to 7. creating, designing, and publishing content on the Web (XHTML, HTML, CSS, JavaScript, 8. GIF, JPEG, PNG, and PDF). The second part of the course covers configuring and maintai9. a web server, including HTTP, access control, and security. Dynamically generated 10. websites and database-driven websites are discussed (CGI, PHP, and JSP). In addition, 11. tools and techniques for maintaining a website, such as log analysis, version control,12. document validation, and page and site analysis, are covered. Prerequisites: CSCI E-1,13. or the equivalent experience.</p> 14.</div> 15.<div style="width: 20%; float: left; margin-left: 2em;" > 16. <p><strong>Hide/Show/Toggle Description</strong></p> 17. <ul> 18. <li><a href="#" id="hide" shape="rect" >Hide</a></li> 19. <li><a href="#" id="show" shape="rect" >Show</a></li> 20. <li><a href="#" id="toggle" shape="rect" >Toggle</a></li> 21. </ul> 22.</div> 23.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

29 of 49 4/1/2008 1:48 PM

In script element (within head element):

Example 8.15 Demonstrated

view plain print ?

$(document).ready(function() { 1. $('a#hide').click(function(event){ 2. $('#cscie12-description2').fadeOut('slow'); 3. event.preventDefault(); 4. }); 5. $('a#show').click(function(event){ 6. $('#cscie12-description2').fadeIn('slow'); 7. event.preventDefault(); 8. }); 9. $('a#toggle').toggle( 10. function(event){ 11. $('#cscie12-description2').fadeOut('slow'); 12. event.preventDefault(); 13. }, 14. function(event){ 15. $('#cscie12-description2').fadeIn('slow'); 16. event.preventDefault(); 17. } 18. ); 19.}); 20.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

30 of 49 4/1/2008 1:48 PM

Check and Uncheck All

Example: check_all.html

JavaScript:

Here we take advantage of an attribute value selector ([name=how]) the ability to retrieve and setattribute values, and also to completely remove attributes. Note too that we iterate through each ofthe checkboxes.

Markup:

$(document).ready(function() { 1. $('#checkall').click(function() { 2. $('[name=how]').attr('checked','checked'); 3. }); 4. $('#uncheckall').click(function() { 5. $('[name=how]').removeAttr('checked'); 6. }); 7. $('#toggle').click(function() { 8. $('[name=how]').each(function (i) { 9. if ($(this).attr('checked')) { 10. $(this).removeAttr('checked'); 11. } else { 12. $(this).attr('checked','checked'); 13. } 14. }); 15. }); 16. }); 17.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

31 of 49 4/1/2008 1:48 PM

<form action="http://minerva.dce.harvard.edu/cgi-bin/echo.cgi" method="get"> 1. <p>How did you hear about us?</p> 2. <p>[<a href="#" id="checkall">check all</a>] 3. [<a href="#" id="uncheckall">uncheck all</a>] 4. [<a href="#" id="toggle">toggle</a>] 5. </p> 6. <ul> 7. <li><input type="checkbox" name="how" value="radio"/>Radio</li> 8. <li><input type="checkbox" name="how" value="newspaper"/>Newspaper</li> 9. <li><input type="checkbox" name="how" value="magazine"/>Magazine</li> 10. <li><input type="checkbox" name="how" value="online"/>Online</li> 11. <li><input type="checkbox" name="how" value="friend"/>Friend</li> 12. </ul> 13. <input type="submit"/> 14.</form> 15.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

32 of 49 4/1/2008 1:48 PM

Duplicate Part of a Form

Example: add_another.html

JavaScript:

Here we take advantage of jQuery clone method to duplicate a node and then insert it into thedocument tree using insertBefore

Markup:

$(document).ready(function() { 1. $('#addphone').click(function() { 2. $('#phone').clone().insertBefore('#addphone'); 3. }); 4. }); 5.

<form action="http://minerva.dce.harvard.edu/cgi-bin/echo.cgi" method="get"> 1. <fieldset> 2. <legend>Contact Information</legend> 3. <div>Name: 4. <input type="text" name="name"/></div> 5. <div id="phone">Phone: 6. <input type="text" name="phone"/> </div> 7. <input type="button" id="addphone" value="Add another phone"/> 8. </fieldset> 9. <div><input type="submit"/></div> 10.</form> 11.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

33 of 49 4/1/2008 1:48 PM

Unobtrusive Javascript

Principles of Unobtrusive JavaScript

SeparationGraceful degredationJS "best-practices"

Grace Degredation for "add another"

One strategy would be to hide the "Add Another" button and make it visible through JavaScript. Wecould go even further by creating the "Add Another" node in JS and then adding it to the page viaJS.

A browser with JS disabled would display form with a single phone field.

Example: add_another_unobtrusive.html With JavaScript disabled in browser:

$(document).ready(function() { 1. $('#addphone').css('display','inline'); 2. $('#addphone').click(function() { 3. $('#phone').clone().insertBefore('#addphone'); 4. }); 5. }); 6.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

34 of 49 4/1/2008 1:48 PM

Without JS and CSS:

With JS and CSS:

Tabs with jQuery

Tab Plugin for jQuery allows the easy creation of tabs from simple markup.

Accessible, Unobtrusive Javascript Tabs wtih jQueryDemos

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

35 of 49 4/1/2008 1:48 PM

Example: tabs.html

Markup:

JS:

<div id="container"> 1. <ul class="anchors"> 2. <li class="on"><a href="#basic">Course</a></li> 3. <li class=""><a href="#description">Description</a></li> 4. <li class=""><a href="#schedule">Schedule</a></li> 5. </ul> 6. 7. <div style="display: block;" id="basic" class="anchor"> 8. <h2>Course Information</h2> 9. <h3>Fundamentals of Website Development</h3> 10. <p> Harvard Extension School, Spring 2007-2008 11. <br/> CSCI E-12 12. <br/> Wednesday, 5:30 to 7:30 pm</p> 13. </div> 14. 15. <div style="display: none;" id="description" class="anchor"> 16. <h2>Course Description</h2> 17. <p>This course provides a foundation ...</p> 18. </div> 19. 20. <div style="display: none;" id="schedule" class="anchor"> 21. <h2>Schedule of Lectures</h2> 22. <ol> 23. <li>Introduction, Internet and Web Basics</li> 24. <li>Markup: XHTML and HTML, Part 1</li> 25. ... 26. </ol> 27. </div> 28.</div> 29.

<script src="js/jquery.js" type="text/javascript"></script> 1.<script src="js/tabs.js" type="text/javascript"></script> 2.<script type="text/javascript"> 3. $(document).ready(function() { 4. $.tabs("container"); 5. }); 6.</script> 7.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

36 of 49 4/1/2008 1:48 PM

A Calendar Widget

jQuery has plugins that will provide an unobtrusive "calendar" widget for picking dates.

Example: date_picker.html

Markup:

JS:

<form action="http://minerva.dce.harvard.edu/cgi-bin/echo.cgi"> 1. <p> 2. Enter a start date: <input class="date" type="text" size="32" name="startdate" id="sta3. </p> 4. <p> 5. Enter an end date: <input class="date" type="text" size="32" name="enddate" id="enddat6. </p> 7. <input type="submit"/> 8.</form> 9.

<style type="text/css">@import url(js/core.ui.datepicker/ui.datepicker.css);</style> 1.<script type="text/javascript" src="js/core.ui.datepicker/ui.datepicker.js"></script> 2.<script type="text/javascript"> 3. $(document).ready(function(){ 4. $('input.date').datepicker(); 5. }) 6.</script> 7.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

37 of 49 4/1/2008 1:48 PM

Slideshow: Thickbox

ThickBoxis a webpage UI dialog widget written in JavaScript on top of the jQuery library. Its function is to show a single image, multiple images, inline content, iframed content, or content served through AJAX in a hybrid modal.

A gallery with no JavaScript -- thumbnail images are linked to the full-sized image with a simple<a href="full/a.png"><img src="thumb/a.png"/></a>:

Thickbox

Example: Gallery with Thickbox

Add Thickbox and give the "a" elemnts a class="gallery":

Gallery

Viewing an individual image:

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

38 of 49 4/1/2008 1:48 PM

Example Galleries with Lightbox, Lightbox 2, and Thickbox

View example galleriesimplemented in Lightbox and Lightbox 2 (using Prototype/Scriptaculous) as well as Thickbox(using jQuery).

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

39 of 49 4/1/2008 1:48 PM

Ajax

AJAX: A New Approach to Web Applications, from Adaptive Path.

by Jesse JamesGarrett

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

40 of 49 4/1/2008 1:48 PM

Ajax Overview

Ajax: A New Approach to Web ApplicationsAJAX (Wikipedia)

Technologies Involved

XHTMLCSSJavaScript

XMLHttpRequest (XHR) objectDocument Object Model (DOM)Possibly: XML, XSLT, XPath, JSON

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

41 of 49 4/1/2008 1:48 PM

Ajax Flow

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

42 of 49 4/1/2008 1:48 PM

Course Search with jQuery

http://minerva.dce.harvard.edu/ajax/course_jquery.html

There is a URL that returns a list of courses given a course group (as an XHTML snippet):

http://minerva.dce.harvard.edu/ajax/course_search?description=protein will return a list of courses whose description contains "protein"http://minerva.dce.harvard.edu/ajax/course_search?description=planet will return a list of courses whose description contains "planet"http://minerva.dce.harvard.edu/ajax/course_search?title=neuro will return a list of courses whose title contains "neuro"http://minerva.dce.harvard.edu/ajax/course_search?title=DNA will return a list of courses whose title contains "DNA"

Note that the search is case-insensitive.

What's involved:

jQuery Javascript libraryServer-side process to generate course list markup (courselist_partial which take a course_group query parameter)Custom Javascript function (getCourseList) to call server-side processJavascript to invokee the custom getCourseList function.

Import jQuery

view plain print ?

<script src="/jquery/jquery.js" type="text/javascript"> </script> 1.<script src="/jquery/jquery.form.js" type="text/javascript"> </script> 2.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

43 of 49 4/1/2008 1:48 PM

jQuery function:

view plain print ?

function getCourseList() { 1. var search_term = $('#search_query').val(); 2. $('#courselist').load( 3. '/ajax/course_search', 4. {'description' : search_term } 5. ); 6. } 7.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

44 of 49 4/1/2008 1:48 PM

Google Maps

Javascript application that uses Ajax to pull in map marker data.

Place "markers" and information on maps via XML data.

CSCI E-12 Campus Map

Markup:

<body onload="load()" onunload="GUnload()"> 1. <div id="map" style="width: 650px; height: 450px"></div> 2.</body> 3.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

45 of 49 4/1/2008 1:48 PM

Marker Data

campus_data_spring2008.xml

Javascript createMarker function:

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

46 of 49 4/1/2008 1:48 PM

function createMarker(point, elem) { 1. // create tabs 2. var infoTabs = []; 3. var tabs = elem.getElementsByTagName("tab"); 4. for (var i = 0; i < tabs.length; i++) { 5. var tab = new GInfoWindowTab( 6. tabs[i].getAttribute("label"), 7. tabs[i].getElementsByTagName("content")[0].textContent 8. ); 9. infoTabs.push(tab); 10. } 11. // create marker, add tabs 12. var marker = new GMarker(point); 13. GEvent.addListener(marker, "click", function() { 14. marker.openInfoWindowTabsHtml(infoTabs); 15. }); 16. return marker; 17.} 18. 19.// load function 20. function load() { 21. if (GBrowserIsCompatible()) { 22. var map = new GMap2(document.getElementById("map")); 23. map.addControl(new GSmallMapControl()); 24. map.addControl(new GMapTypeControl()); 25. map.addControl(new GOverviewMapControl()); 26. // center 42.375492,-71.117613 27. map.setCenter(new GLatLng(42.375492,-71.117613), 16); 28. map.setMapType(G_HYBRID_TYPE); 29. // Download the data in data.xml and load it on the map. The format we 30. // expect is: 31. // <markers> 32. // <marker lat="37" lng="-122"><content>...</content></marker> 33. // <marker lat="30" lng="-100"><content>...</content></marker> 34. // </markers> 35. GDownloadUrl("campus_data.xml", function(data) { 36. var xml = GXml.parse(data); 37. var markers = xml.documentElement.getElementsByTagName("marker"); 38. for (var i = 0; i < markers.length; i++) { 39. var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), 40. parseFloat(markers[i].getAttribute("lng"))); 41. var marker = createMarker(point, markers[i]); 42. map.addOverlay(marker); 43. } 44. }); 45. } 46. } 47.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

47 of 49 4/1/2008 1:48 PM

Conferences: Loading with HTML

Example

PageMarkupJS

Serverselect-conferencesearch

Markup:

JS:

<form id="search-form" action="http://minerva.dce.harvard.edu/cgi-bin/echo.cgi"> 1. 2. <div id="select-conference"> </div> 3. <input type="submit"/> 4.</form> 5.<hr/> 6.<div id="results_section"> </div> 7.

$(document).ready(function(){ 1. setConferenceOptions(); 2. $('#search-form').submit(function(e) { 3. updateResults(); 4. e.preventDefault(); 5. }); 6. }); 7. function setConferenceOptions() { 8. $('#select-conference').load('ajax/select-conference'); 9. } 10. function updateResults() { 11. var selectedconf = $('#conference').fieldValue(); 12. var loading = $('<p>Loading...<br/><img src="images/ajax-loader-bar.gif" alt="loadin13. $('#results_section').html(loading); 14. $('#results_section').load('ajax/search',{'conference':selectedconf}); 15. } 16.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

48 of 49 4/1/2008 1:48 PM

Conferences: JSON

Instead of returning HTML to be put into the page, our server-side process will return JSON(JavaScript Object Notation). We can then process the JSON data into the page.

JSON data example:

And the JS to process it:

{'schools':[ 1.{ 2. name:"Brown University", 3. href:"http://www.brown.edu", 4. division:"I", 5. conference:"Ivy Group", 6. conf_href:"http://www.ivyleaguesports.com/", 7. state:"Rhode Island" 8.}, 9.{ 10. name:"Harvard University", 11. href:"http://www.harvard.edu", 12. division:"I", 13. conference:"Ivy Group", 14. conf_href:"http://www.ivyleaguesports.com/", 15. state:"Massachusetts" 16.}, 17./* removed schools for clarity*/ 18.]} 19.

function updateResults() { 1. var selectedconf = $('#conference').fieldValue(); 2. var loading = $('<p>Loading...<br/><img src="images/ajax-loader-bar.gif" alt="loading"3. $.getJSON( 4. 'ajax/search-json', 5. {'conference':selectedconf}, 6. function(data){ 7. $('#results_section').html(''); 8. $.each(data.schools, function(i,school){ 9. $('<p>'+ school.name + '</p>').appendTo('#results_section'); 10. }); 11. }); 12.} 13.

Javascript and Ajax http://cscie12.dce.harvard.edu/lecture_notes/2007-08/20080319/handout...

49 of 49 4/1/2008 1:48 PM

Conferences: XML

Return XML data:

And the JS changes slightly to process XML instead of JSON:

Table of Contents | All Slides | Link List | Examples | CSCI E-12

function updateResults() { 1. $('#results_section').html(''); 2. var selectedconf = $('#conference').fieldValue(); 3. $.get( 4. 'ajax/search-xml', 5. {'conference':selectedconf}, 6. function(xml){ 7. $(xml).find('school').each(function(){ 8. $('<p>'+ $(this).attr('name') + '</p>').appendTo('#results_section'); 9. }) 10. }); 11.} 12.