CSSE 290 Web Programming

Lecture 19: More events, Ajax intro

Reading: 11.1, 12.1

Attribution:Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.

Otherwise noted: Claude Anderson was given permission to modify the slides for CSSE 290 at Rose-Hulman by author Jessica Miller. The authors' original slides, based on Web Programming Step by Step, can be seen at http://webstepbook.com.
Some of the examples in some days' slides are from David Fisher at Rose-Hulman, who was kind enough to allow me to use them. My intention is to mark these examples with [DSF].

Valid HTML Valid CSS!

11.1: Event-Handling

JavaScript events

abort blur change click dblclick error focus
keydown keypress keyup load mousedown mousemove mouseout
mouseover mouseup reset resize select submit unload

Attaching event handlers the Prototype way

element.onevent = function;
element.observe("event", function);
// call the playNewGame function when the Play button is clicked
$("play").observe("click", playNewGame);

The event object

function name(event) {
	// an event handler function ...
}
method / property name description
type what kind of event, such as "click" or "mousedown"
element() * the element on which the event occurred
stop() ** cancels an event
stopObserving() removes an event handler

Mouse events

clicking
click user presses/releases mouse button on the element
dblclick user presses/releases mouse button twice on the element
mousedown user presses down mouse button on the element
mouseup user releases mouse button on the element
movement
mouseover mouse cursor enters the element's box
mouseout mouse cursor exits the element's box
mousemove mouse cursor moves around within the element's box

Mouse event objects

The event passed to a mouse handler has these properties:

mouse event
property/method description
clientX, clientY coordinates in browser window
screenX, screenY coordinates in screen
offsetX, offsetY coordinates in element (non-standard)
pointerX(),
pointerY() *
coordinates in entire web page
isLeftClick() ** true if left button was pressed

Mouse event example

<pre id="target">Move the mouse over me!</pre>
window.onload = function() {
	$("target").observe("mousemove", showCoords);
};

function showCoords(event) {
	$("target").innerHTML = 
		  "pointer: (" + event.pointerX() + ", " + event.pointerY() + ")\n"
		+ "screen : (" + event.screenX + ", " + event.screenY + ")\n"
		+ "client : (" + event.clientX + ", " + event.clientY + ")";
}
Move the mouse over me!

The keyword this

this.fieldName                  // access field
this.fieldName = value;          // modify field

this.methodName(parameters);    // call method

Event handler binding

window.onload = function() {
	$("textbox").observe("mouseout", booyah);   // bound to text box here
	$("submit").observe("click", booyah);       // bound to submit button here
};

function booyah() {           // booyah knows what object it was called on
	this.value = "booyah";
}

Fixing redundant code with this

<fieldset>
	<label><input type="radio" name="ducks" value="Huey"  /> Huey</label>
	<label><input type="radio" name="ducks" value="Dewey" /> Dewey</label>
	<label><input type="radio" name="ducks" value="Louie" /> Louie</label>
</fieldset>
function processDucks() {
	if ($("huey").checked) {
		alert("Huey is checked!");
	} else if ($("dewey").checked) {
		alert("Dewey is checked!");
	} else {
		alert("Louie is checked!");
	}
	alert(this.value + " is checked!");
}

Page/window events

namedescription
load, unload the browser loads/exits the page
resize the browser window is resized
error an error occurs when loading a document or an image
contextmenu the user right-clicks to pop up a context menu
window.onload = function() { ... };
document.observe("dom:loaded", function() {
	// attach event handlers, etc.
});

Keyboard/text events

name description
keydown user presses a key while this element has keyboard focus
keyup user releases a key while this element has keyboard focus
keypress user presses and releases a key while this element has keyboard focus
focus this element gains keyboard focus
blur this element loses keyboard focus
select this element's text is selected or deselected)

Key event objects

property name description
keyCode ASCII integer value of key that was pressed
(convert to char with String.fromCharCode)
altKey, ctrlKey, shiftKey true if Alt/Ctrl/Shift key is being held
Prototype's key code constants
Event.KEY_BACKSPACE Event.KEY_DELETE Event.KEY_DOWN Event.KEY_END
Event.KEY_ESC Event.KEY_HOME Event.KEY_LEFT Event.KEY_PAGEDOWN
Event.KEY_PAGEUP Event.KEY_RETURN Event.KEY_RIGHT Event.KEY_TAB
Event.KEY_UP

Form events

event name description
submit form is being submitted
reset form is being reset
change the text or state of a form control has changed
activate clear disable enable
focus getValue present select

Prototype form shortcuts

$F("formID")["name"]
$F("controlID")

Stopping an event

<form id="exampleform" action="http://foo.com/foo.php">...</form>
window.onload = function() {
	$("exampleform").observe("submit", checkData);
};

function checkData(event) {
	if ($F("city") == "" || $F("state").length != 2) {
		alert("Error, invalid city/state.");  // show error message 
		event.stop();
		return false;
	}
}

12.1: Ajax Concepts

Synchronous web communication

synchronous communication

Web applications and Ajax

Ajax bleach

Asynchronous web communication

synchronous communication

XMLHttpRequest

A typical Ajax request

request
  1. user clicks, invoking an event handler
  2. handler's code creates an XMLHttpRequest object
  3. XMLHttpRequest object requests info from server
  4. server retrieves appropriate data, sends it back
  5. XMLHttpRequest fires an event when data arrives
    • we attach a handler function to this event (callback)
  6. callback event handler processes the data and displays it

An aside: Creating a new anonymous object

var name = {
	fieldName: value,
	...
	fieldName: value
};
var p = {
	x: 4,
	y: 3,
	distanceFromOrigin: function() {
		return Math.sqrt(this.x * this.x + this.y * this.y);
	}
};
alert(p.x + ", " + p.y + ", dist=" + p.distanceFromOrigin());

Prototype's Ajax model

new Ajax.Request("url", {
	option : value,
	option : value,
	...
	option : value
});

Prototype Ajax options

option description
method how to fetch the request from the server (default "post")
asynchronous should request be sent asynchronously in the background? (default true, for good reasons)
parameters query parameters to pass to the server, if any (as a string or object)
onSuccess event: request completed successfully
onFailure event: request was unsuccessful
onException event: request has a syntax error, security error, etc.
others: contentType, encoding, requestHeaders; events: onCreate, onComplete, on### (for HTTP error code ###, example on404)

Prototype Ajax example

	new Ajax.Request("foo/bar/mydata.txt", {
		method: "get",
		onSuccess: myAjaxSuccessFunction
	});
	...

function myAjaxSuccessFunction(ajax) {
	do something with ajax.responseText;
}

Ajax response object's properties

property description
status the request's HTTP result code (200 = OK, etc.)
statusText HTTP status code text
responseText the entire text of the fetched file, as a string
responseXML,
responseJSON
the entire contents of the fetched file, in other formats (seen later)
function myAjaxSuccessFunction(ajax) {
	alert(ajax.responseText);
}

Handling Ajax errors

	new Ajax.Request("url", {
		method: "get",
		onSuccess: functionName,
		onFailure: ajaxFailure,
		onException: ajaxFailure
	});
	...
function ajaxFailure(ajax, exception) {
  alert("Error making Ajax request:" + 
	"\n\nServer status:\n" + ajax.status + 
    " " + ajax.statusText + 
	"\n\nServer response text:\n" + ajax.responseText);
  if (exception) {
	throw exception;
	}
}

Passing query parameters to a request

new Ajax.Request("lookup_account.php", {
	method: "get",
	parameters: {name: "Ed Smith", age: 29, password: "abcdef"},
	onFailure: ajaxFailure,
	onException: ajaxFailure
});
...

Creating a POSTrequest

new Ajax.Request("url", {
	method: "post",
	parameters: {name: value, name: value, ..., name: value},
	onSuccess: functionName,
	onFailure: functionName,
	onException: functionName
});