chapter 6 javascript and ajax

22
Chapter 6 JavaScript and AJAX

Upload: herman-colon

Post on 31-Dec-2015

75 views

Category:

Documents


0 download

DESCRIPTION

Chapter 6 JavaScript and AJAX. Objectives. Explain the purpose and history of JavaScript Describe JavaScript features Explain the event-driven nature of JavaScript and name DOM events Explain how JavaScript dialog boxes work Use JavaScript to validate forms - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 6 JavaScript and AJAX

Chapter 6JavaScript and AJAX

Page 2: Chapter 6 JavaScript and AJAX

Objectives

• Explain the purpose and history of JavaScript• Describe JavaScript features• Explain the event-driven nature of JavaScript

and name DOM events• Explain how JavaScript dialog boxes work• Use JavaScript to validate forms• Explain Ajax operation, synchronous and

asynchronous• Use Ajax for simple data lookups• Explain Ajax cost and benefits

Page 3: Chapter 6 JavaScript and AJAX

JavaScript History

• Originally "LiveScript"– Renamed for marketing purposes

• Not directly related to Java

• International standard as ECMAScript– European Computer Manufacturers Assoc.

• JavaScript 1.8 similar to ECMAScript 3

• Similar JScript developed by Microsoft

Page 4: Chapter 6 JavaScript and AJAX

JavaScript Features (1/2)

• A scripting language– informal syntax, minimal coding

• Dynamic variable typing– boolean, number, string, function, object– implicit type conversions– potential problem w.r.t. correctness, security

• First-class functions– Functions can be passed by variable

Page 5: Chapter 6 JavaScript and AJAX

JavaScript Features (2/2)

• Event-driven– Programs respond to user interface actions (mouse

movement, click, keystroke, etc.)

• Server-Side or Client-Side– JavaScript can be used on either platform– Most commonly used client-side for user interface

enhancement

• Client-Side functionality– JavaScript functions can add, change, or delete any

HTML element– Changes are dynamically re-displayed

Page 6: Chapter 6 JavaScript and AJAX

Adding JavaScript to HTML

• JavaScript code can be placed anywhere in an HTML document

• Typically placed at the end of <head>• Delimited by <script>…</script>

<head> <title>JavaScript Demo</title> <script type="text/javascript"> function sayHello() { alert("Hello!"; } </script></head>

Page 7: Chapter 6 JavaScript and AJAX

Invoking JavaScript Code

• JavaScript functions can be tied to DOM events on individual HTML elements– using onX="function()", where 'X' is an event

<script type="text/javascript"> function color(button, color) { button.style.background=color }</script>

<input type="button" value="Click Me" onmouseover="color(this, #FF0000)"

onmouseout="color(this, #E0E0E0)" /> red

gray

Click Me

Click Me

self-reference

Page 8: Chapter 6 JavaScript and AJAX

DOM Events

User-Initiated• click• dlbclick• keydown• keyup• keypress• mouseover• mouseout• mousedown• mouseup• mousemove• change• resize

• scroll• select• blur• focus• reset• submit

Browser-Initiated• load• unload• error• abort

Page 9: Chapter 6 JavaScript and AJAX

Dialog Boxes

• Dialog boxes can be used to – inform the user of

errors or events

– confirm actions initiated by the user

Page 10: Chapter 6 JavaScript and AJAX

User Action Confirmation Dialog

<script type="text/javascript"> function confirmDelete() { var answer = confirm("Are you sure you want" + "to delete this player?"); return answer }</script>

<form method="post" action="/delete"> ...<p><input type="submit" value="Delete"

onclick="return confirmDelete()" /></p></form>

if the user clicks"Cancel", theform will NOTbe submitted

Page 11: Chapter 6 JavaScript and AJAX

Form Validation

<script> function validate() { if (document.getElementById("name").value.length == 0) { alert("Please complete the required fields\n" + "and resubmit."); return false; } return true; }</script>

<h3>Add Player:</h3><form id="form1" action="addplayer" onsubmit="return validate()" > <p>Name: <input type="text" id="name" /></p> ... <p><input type="submit" value="Register" /></p></form>

if the procedurereturns false, theform will NOTbe submitted

Page 12: Chapter 6 JavaScript and AJAX

HTML Manipulation<script> function validate() { if (document.getElementById("name").value.length == 0) { alert("Please complete the required fields\n" + "and resubmit."); document.getElementById("nameflag").innerHTML = "* " return false; } document.getElementById("nameflag").innerHTML = "" return true; }</script>

<h3>Add Player:</h3><form id="form1" action="addplayer" onsubmit="return validate()" > <p><span id="nameflag"></span>

Name: <input type="text" id="name" /></p> ... <p><input type="submit" value="Register" /></p></form>

Page 13: Chapter 6 JavaScript and AJAX

Ajax

• Ajax allows a JavaScript procedure to execute an HTTP transaction in the background

• Ajax can be used to fetch information, images, etc., or to pass information to the server in order to enhance the user experience of a web page

Page 14: Chapter 6 JavaScript and AJAX

Ajax

Page 15: Chapter 6 JavaScript and AJAX

Ajax Setup

• An XMLHttpRequest object is created to channel HTTP transactions

<script type="text/javascript"> window.onload = createXMLHttpRequest;

function createXMLHttpRequest() { try { // for Firefox, IE7, Opera xmlreq = new XMLHttpRequest(); } catch (e) { try { // for IE6 xmlreq = new ActiveXObject('MSXML2.XMLHTTP.5.0'); } catch (e) { xmlreq = null; } } } ...

Page 16: Chapter 6 JavaScript and AJAX

Synchronous Ajax

• Ajax can be used in simple "synchronous" mode, in which the user interface is blocked (unusable) while a transaction completes

var url = "...server URL..."

xmlreq.open('GET', url, false);

xmlreq.send(null);

var response = xmlreq.responseText;

Send HTTP request

Receive HTTP response

Page 17: Chapter 6 JavaScript and AJAX

Asynchronous Ajax

• With asynchronous Ajax, the user interface continues to operate while the client listens for a response

xmlreq.open('GET', url, true);xmlreq.onreadystatechange = function() { if (xmlreq.readyState == 4) if (xmlreq.status == 200) var response = xmlreq.responseText; else alert('Ajax failed; status: ' + xmlreq.status);}xmlreq.send(null);

Page 18: Chapter 6 JavaScript and AJAX

Ajax ReadyState Values

Ready State Significance

0 Uninitialized Request not yet opened

1 Loading Not yet sent

2 Loaded Sent; no information available

3 Interactive Partial response received

4 Completed Response complete

Page 19: Chapter 6 JavaScript and AJAX

Ajax Example (1/2)

function checkNumber(custNr) { if (custNr.length < 9) return var url = "getname?custnr=" + custNr xmlreq.open('GET', url, true) xmlreq.onreadystatechange = function() { if (xmlreq.readyState == 4) if (xmlreq.status == 200) document.getElementById('name').innerHTML = xmlreq.responseText } xmlreq.send(null)}

<p><input type="text" id="custnr" onkeyup="checkNumber(this.value)" /> <span id="name"></span></p>

Page 20: Chapter 6 JavaScript and AJAX

Ajax Example (2/2)

import java.io.*;import javax.servlet.http.*;

public class NameLookup extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {

String custNr = req.getParameter("custnr"); String custName = ... lookup customer name ... ;

PrintWriter out = res.getWriter(); res.setContentType("text/plain"); out.write(custName); out.close(); }}

Page 21: Chapter 6 JavaScript and AJAX

Ajax Benefits and Costs

• Benefits– Rich and responsive user interfaces– Novel web applications

• Costs– Increased network and server load– Increased complexity of design and coding

Page 22: Chapter 6 JavaScript and AJAX

Review

• JavaScript purpose and history• JavaScript and the DOM event model• JavaScript dialog boxes• JavaScript and form validation• Ajax operation, synchronous and

asynchronous• Simple data lookup with Ajax• Ajax costs and benefits