CPS 353: Internet Programming

JavaScript Events and jQuery; Ajax, XML, and JSON

Simon Miner

Gordon College

Last Modified: 11/06/2013

Selected content adapted from material by Marty Stepp, Jessica Miller, and Victoria Kirst © 2012. Used by permission.

Agenda

Check-in

JavaScript Frameworks

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 with jQuery

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

The event object

function name(event) {
	// an event handler function ...
}
method / property name description
pageX, pageY mouse position at the time the event occurred
type what kind of event, such as "click" or "mousedown"
preventDefault() prevent the default action of the event (i.e. following a limk)
stopPropagation() stop the event from "bubbling" up to other events

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 example

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

function showCoords(event) {
	$("target").innerHTML = 
		  "pointer: (" + event.pageX() + ", " + event.pageY() + ")\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

$(document).ready( function() {
	$("textbox").on("mouseout", booyah);   // bound to text box here
	$("submit").on("click", booyah);       // bound to submit button here
});

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

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).ready( 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
which 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

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

Stopping an event

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

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

Timer events

timer
method description
setTimeout(functiondelayMS); arranges to call given function after given delay in ms
setInterval(functiondelayMS); arranges to call function repeatedly every delayMS ms
clearTimeout(timerID);
clearInterval(timerID);
stops the given timer so it will not call its function

setTimeout example

<button onclick="delayMsg();">Click me!</button>
<span id="output"></span>
function delayMsg() {
	setTimeout(booyah, 5000);
	document.getElementById("output").innerHTML = "Wait for it...";
}

function booyah() {   // called when the timer goes off
	document.getElementById("output").innerHTML = "BOOYAH!";
}

setInterval example

var timer = null;  // stores ID of interval timer

function delayMsg2() {
	if (timer == null) {
		timer = setInterval(rudy, 1000);
	} else {
		clearInterval(timer);
		timer = null;
	}
}

function rudy() {   // called each time the timer goes off
	document.getElementById("output").innerHTML += " Rudy!";
}

Passing parameters to timers

function delayedMultiply() {
	// 6 and 7 are passed to multiply when timer goes off
	setTimeout(multiply, 2000, 6, 7);
}
function multiply(a, b) {
	alert(a * b);
}

Common timer errors

Example

Multiplication Quiz - modified from textbook case study

12.1: Ajax Concepts

Synchronous web communication

synchronous communication

Web applications and Ajax

Ajax bleach

Asynchronous web communication

synchronous communication

12.2: Using XMLHttpRequest

XMLHttpRequest (and why we won't use it)

A typical Ajax request

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

jQuery's $.ajax() Method

$.ajax( "url"
	{
		option : value,
		option : value,
		...
		option : value
	}
);

$.ajax() configuration options

option description
url URL to submit the request to
data data to send with the request, an associative array that will be converted to a query string
type HTTP method of request, GET or POST
dataType type of content to expect in the response (html, json, xml, etc.)
success function to run if the request succeeds (response data is passed as a paramter)
error function to run if the request fails (gets raw request and status code as paramters)
complete function to run regardless if the request succeeds or fails
others: async, cache, timeout, and many more...

$.ajax() example

$.ajax({
  url: "post.php",
  data: { id: 123 },
  type: "GET",
  dataType : "json",
  success: function( json ) {
    $( "<h1/>" ).text( json.title ).appendTo( "body" );
    $( "<div class=\"content\"/>").html( json.html ).appendTo( "body" );
  },
  error: function( xhr, status ) {
    alert( "Sorry, there was a problem!" );
  },
  complete: function( xhr, status ) {
    alert( "The request is complete!" );
  }
});

Ajax Events

event description
ajaxStart triggered when an Ajax reqeust starts and there are no other Ajax requests running (global)
success invoked if the request is successful (local)
error invoked if there is an error in the request (success and error will never both be called) (local)
complete called regardless of response state, always invoked (local)
ajaxStop triggered when there are no more Ajax requests being processed (global)

Ajax Event Example

// Setting up a loading indicator using Ajax Events
$( "#loading_indicator" ).ajaxStart(function() {
  $( this ).show();
}).ajaxStop(function() {
  $( this ).hide();
});

XMLHttpRequest security restrictions

Ajax security error

Troubleshooting and debugging Ajax

Firebug Ajax

Rails and Ajax

<%= button_to 'Add to Cart', line_items_path(product_id: product), remote: true %>

12.3: XML

The bad way to store data

My note:
BEGIN
	TO: Tove
	FROM: Jani
	SUBJECT: Reminder
	MESSAGE (english):
		Hey there,
		Don't forget to call me this weekend!
END

What is XML?

Anatomy of an XML file

<?xml version="1.0" encoding="UTF-8"?>  <!-- XML prolog -->
<note>                                  <!-- root element -->
	<to>Tove</to>
	<from>Jani</from>                     <!-- element ("tag") -->
	<subject>Reminder</subject>           <!-- content of element -->
	<message language="english">          <!-- attribute and its value -->
		Don't forget me this weekend!
	</message>
</note>

Uses of XML

Pros and cons of XML

What tags are legal in XML?

Doctypes and Schemas

XML and Ajax

Ajax bleach

XML DOM tree structure

node tree
<?xml version="1.0" encoding="UTF-8"?>
<categories> 
  <category>children</category> 
  <category>computers</category> 
  ... 
</categories>

Recall: Javascript XML (XHTML) DOM

The DOM properties and methods* we already know can be used on XML nodes:

Navigating the node tree

Using XML data in a web page

  1. use Ajax to fetch data
  2. use DOM methods to examine XML:
    • XMLnode.getElementsByTagName("tag")
  3. extract the data we need from the XML:
    • XMLelement.getAttribute("name"), XMLelement.firstChild.nodeValue, etc.
  4. create new HTML nodes and populate with extracted data:
    • document.createElement("tag"), HTMLelement.innerHTML
  5. inject newly-created HTML nodes into page
    • HTMLelement.appendChild(element)

12.4: JSON

Pros and cons of XML

JavaScript Object Notation (JSON)

json
json

JavaScript Object Notation (JSON): Data format that represents data as a set of JavaScript objects

Recall: JavaScript object syntax

var person = {
	name: "Philip J. Fry",                           // string
	age: 23,                                         // number
	"weight": 172.5,                                 // number
	friends: ["Farnsworth", "Hermes", "Zoidberg"],   // array
	getBeloved: function() { return this.name + " loves Leela"; }
};
alert(person.age);                                 // 23
alert(person["weight"]);                           // 172.5
alert(person.friends[2]));                         // Zoidberg
alert(person.getBeloved());                        // Philip J. Fry loves Leela

An example of XML data

<?xml version="1.0" encoding="UTF-8"?>
<note private="true">
	<from>Alice Smith (alice@example.com)</from>
	<to>Robert Jones (roberto@example.com)</to>
	<to>Charles Dodd (cdodd@example.com)</to>
	<subject>Tomorrow's "Birthday Bash" event!</subject>
	<message language="english">
		Hey guys, don't forget to call me this weekend!
	</message>
</note>

The equivalant JSON data

{
	"private": "true",
	"from": "Alice Smith (alice@example.com)",
	"to": [
		"Robert Jones (roberto@example.com)",
		"Charles Dodd (cdodd@example.com)"
	],
	"subject": "Tomorrow's \"Birthday Bash\" event!",
	"message": {
		"language": "english",
		"text": "Hey guys, don't forget to call me this weekend!"
	}
}

Browser JSON methods

method description
JSON.parse(string) converts the given string of JSON data into an equivalent JavaScript object and returns it
JSON.stringify(object) converts the given object into a string of JSON data (the opposite of JSON.parse)

JSON expressions exercise

var data = JSON.parse(ajax.responseText);
{
	"window": {
		"title": "Sample Widget",
		"width": 500,
		"height": 500
	},
	"image": { 
		"src": "images/logo.png",
		"coords": [250, 150, 350, 400],
		"alignment": "center"
	},
	"messages": [
		{"text": "Save", "offset": [10, 30]}
		{"text": "Help", "offset": [ 0, 50]},
		{"text": "Quit", "offset": [30, 10]},
	],
	"debug": "true"
}

Given the JSON data at right, what expressions would produce:

var title = data.window.title;
var coord = data.image.coords[2];
var len = data.messages.length;
var y = data.messages[len - 1].offset[1];

Bad style: the eval function

// var data = JSON.parse(ajax.responseText);
var data = eval(ajax.responseText);   // don't do this!
...

Milestone 7