Dr James Denholm-Price [email protected] XP Lecture 9 WEB APP’S: WORKING WITH THE...

40
Dr James Denholm-Price [email protected] XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1
  • date post

    19-Dec-2015
  • Category

    Documents

  • view

    217
  • download

    0

Transcript of Dr James Denholm-Price [email protected] XP Lecture 9 WEB APP’S: WORKING WITH THE...

Page 1: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Dr James [email protected]

XP

Lecture 9WEB APP’S:

WORKING WITH THE DOCUMENT OBJECT MODEL

1

Page 2: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Next week (6th December 2010)

• 1-3PM Lab– In-class “assignment” (aka “test 2”).– Based-on exercise 6 “lecturers.xml” and

“lecturers.xsl”– Finish ex6 before and bring the files with you!

2

Page 3: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

OBJECTIVES: lecture 8 “DOM”

Revise/introduce web applications and client-side JavaScript very briefly

Reintroduce the W3C document object model (DOM) client-side

Create and load a document object into an existing document

Apply an XSLT transformation to a document Use JavaScript to modify the contents of an HTML

document

3

Page 4: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

OBJECTIVES: lecture 9 “DOM”

Submit data from an HTML form over HTTP. Retrieve XML from PHP Use JavaScript to modify the attribute values of a

document element

I.e. Writing a client-server web application with much of the application running on the client

4

Page 5: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Reminder

• Last lecture:– JavaScript intro.– jQuery & Transform– Steps:

1.Load HTML, CSS, JavaScript etc.2.Onload load XML & XSL3.Run the transformation4.Insert the output HTML into the main

document5

URL

Page 6: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

No Server RoundtripThe user experience can be improved by eliminating the delay, making the server roundtrip occur in the background.

1. User requests page from server.2. Page loads in client.3. User enters data, browser sends data asynchronously.

The server receives HTTP request for page + data, processes the request + data and returns the new page.

4. User continues to interact with the page (no waiting!)

► Run most of the application on the client.► Submit data asynchronously (“web 2.0”).

6

Page 7: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

SERVER-SIDE

PHP headers etc.

7

Page 8: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Client-server interaction code• The web form allows the user to

– Enter new data => submission needs to be handled server-side && client-side

– Sort/filter data => client-side (later – more JavaScript)• Server-side PHP allows us to:

– Validate data input (security & DB integrity).– Return data/headers in response.

• E.g. HTTP 1.0/1.1 defines a number of codes we could use to feed-back to the client-side such as

– header('HTTP/1.0 503 Service Unavailable');– header('HTTP/1.0 400 Bad Request');– header('HTTP/1.1 500 Internal Server Error');– header('Content-Type: text/plain');

vs.header('Content-Type: application/xml'); etc...

8

Page 9: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

9

HTTP Content-type

• Part of the HTTP header that specifies the content of the document (from the server.)– E.g.

• Content-type: application/pdf, image/gif etc.• Content-type: text/html from the HTML4 spec. text/plain

• … application/xml from the XML spec.… text/xml

• … application/xhtml+xml from the XHTML spec.

– Text types don’t get parsed as XML so no DOM

Page 10: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

10

Serving XML: PHP<?php

//script to return data as XML:header('Content-Type: application/xml');echo '<?xml version="1.0" encoding="UTF-8"?>';

//connect to DBinclude('/home/ku13043/connect_mysqli.php');$db = @mysqli_select_db('ku13043');

//no database if (!$db) { header('HTTP/1.0 503 Service Unavailable'); die('<error type="Database connection failed" />'); }

Page 11: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

11

Serving XML: PHP//Retrieve clist data: $sql = "SELECT first,last,street,city,state,zip,amount,date" . . " FROM clist"; $data = mysqli_query($sql); echo "<persons>"; while ($row=mysqli_fetch_row($data)) { echo "<person>"; printf("<first_name>%s</first_name>", htmlspecialchars($row[0])); printf("<last_name>%s</last_name>", htmlspecialchars($row[1])); // ... ETC for $row[2] to $row[7] ... echo "</person>";}echo '</persons>';?>

Page 12: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Processing form submission: PHP<?php header('Content-Type: text/plain'); //connect to DB include('/home/ku13043/connect_mysql.php'); $db = @mysqli_select_db('ku13043');

//no database if (!$db) { header('HTTP/1.0 503 Service Unavailable'); die('The database is currently down ...'); }

//bad data if (count($_GET) < 8) { header('HTTP/1.0 400 Bad Request'); die('There was a problem processing the request...';}

12

Page 13: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Processing form submission: PHP//insert data $sql = 'INSERT INTO clist

(first,last,street,city,state,zip,amount,date) VALUES ("' . $_GET['first'] . '","' . $_GET['last'] . '","' . $_GET['street'] . '","' . $_GET['city'] . '","' . $_GET['state'] . '","' . $_GET['zip'] . '",' . $_GET['amount'] . ',"' . $_GET['date'] . '")';

$rc = mysqli_query($sql);

//simple check for problemsif ($rc && mysqli_affected_rows()==1) { header('HTTP/1.1 200 OK'); //success!} else { header('HTTP/1.1 500 Internal Server Error'); echo 'Rows=' . mysqli_affected_rows() . ' sql=' . $sql; }

?>

13

Page 14: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

<Aside> Security: SQL Injection

• That query is dangerous– $sql = 'INSERT INTO clist

(first,last,street,city,state,zip,amount,date) VALUES ("' . $_GET['first'] . '","' . $_GET['last'] . '","' . $_GET['street'] . '","' . $_GET['city'] . '","' . $_GET['state'] . '","' . $_GET['zip'] . '",' . $_GET['amount'] . ',"' . $_GET['date'] . '")';

– Should instead at least escape “dodgy” input in each $_GET with mysql_real_escape_string($_GET[...]) or addslashes($_GET[...])

• SQL injection: further reading from php.net...

14

Page 15: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

CLIENT-SIDE

More JavaScript & jQuery

15

Page 16: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Client-side data submission• Last time XML & XSL loaded and transformed in one go via jQuery

& Transform plugin:– $("#id").transform({

xml:"data.xml", xsl:"data.xsl"

});• But if we allow form-submission to alter the server-side state we

have two choices:1) Reload the XML every time to update the client-side state.2) Alter the client-side state to reflect the server-side changes.

• To do (1) we can simply redo the Transform after the data submission returns (successful or not).

• To do (2) we must update the client-side XML iff the data succeeds.

16

Page 17: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

(1) Form-submission with reload• The client-side HTML includes

– <form name="webform" id="webform" method="post" enctype="text/plain" onsubmit="addRecord()" action="#">

• JavaScriptfunction addRecord() { //return false; //from lecture 8... ;-)

//full control over jQuery ajax request: $.ajax({ type: 'GET', //send simple form data via HTTP GET url: 'clist.php' , //the destination URL //... etc (PTO) ... }); }

17

Page 18: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Form-submission with reload$.ajax({ type: 'GET', url: 'clist.php' ,

//serialize turns form elements into a query string data: $('#webform').serialize(),

//stop browsers aggressively caching HTTP requests, cache: false,

success: function() { //redo the transform by reloading the XML data from the server $("#ctable").transform({xml:"clistXML.php", xsl:"clist.xsl"}); },

error: function (xhr,status) { alert('HTTP error '+status+' sending data ...\n' +

xhr.responseText); }

}); 18

Page 19: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Dr James [email protected]

XP

8.1 Client-side nodes

Manipulating a dynamic document using the DOM

19url

Page 20: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Working with the document object

• Document content is stored in nodes in the browser (XML or HTML)

• Nodes can represent any item (element, attribute, etc.)

• Nodes are organized in a node tree– C.f. XPath

20

Page 21: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Sample node tree

21

Page 22: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Node terminology

• Parent node:– Contains other nodes

• Child node:– Contained by a parent

• Sibling nodes:– Share same parent

• Attribute nodes:– Do not have parents (ownerElement)

22

Page 23: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Working with node properties

31

Page 24: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Adding new records• Clone an existing record

– var clone = node.cloneNode(true);• Set property values by setting nodeValue for firstChild of

each element• Syntax:

clone.childNodes[i].firstChild.nodeValue=text• To reference the contents of form fields:

– document.formName.fieldName.value– document.forms['formName'] .elements['elementName'].value

• To add new node use appendChild()

36

Page 25: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Tutorial page• Form named webform with properties for each

child element of <person>: first, last, street, city, state, zip, amount, date

• Each such element’s value (contents) is (in IE)– document.webform.first.value

• Cross-browser (DOM0/BOM)– document.forms['webform'].elements ['first'].value

or– document.forms.webform.elements .first.value

37

Page 26: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Dr James [email protected]

XP

8.2 Client-side nodes

Modifying XSLT properties using attributes in the DOM

(Carey 1e Tutorial 9)

41

Page 27: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Tutorial: Choosing how to sort

• XSLT attributes can be modified inside the XSLTDoc object & the transform ran again

• <xsl:sort select="date" data-type="text"order="descending" />

• Choose what values to give the attributes from form elements, e.g. radio buttons to select between values:– <input type="radio" name="sort" /><input type="radio" name="sort" /><input type="radio" name="sort" /><input type="radio" name="sort" checked="checked" />

• Identically-named radio button & check boxes appear as an array:– document.webform.sort[i].checked is true/false

43

Page 28: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Tutorial: Sorting the XML

• Locate the <xsl:sort> element – var sortNode = XSLTDoc.getElementsByTagName("xsl:sort")[0];

• Assign appropriate values, e.g.:– if (document.webform.order[0].checked)

order = "ascending";else order = "descending";sortNode.setAttribute("order", order);//...etc.

• Trigger a re-sort every time a radio button is clicked:– <input type="radio" name="order" checked="checked" onClick="changeStyle()" />

44

URL

Page 29: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Tutorial: Filtering nodes

• Using XPath we can choose what set of nodes the select in the company list by modifying– <xsl:param name="group" select="//person" />

– E.g. amount>=500 would select certain nodes, as-if: <xsl:param name="group" select="//person[amount>=500]" />

45

URL

Page 30: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Implementation• Sorting & filtering needs access to the client-side DOM document • Last time XML & XSL loaded and transformed in one go :

– $("#id").transform({xml:"data.xml", xsl:"data.xsl"});• This time we need full control:

– //Global vars xmldoc & xsldoc: – xmldoc = $.ajax({ type: "GET", url: "clistXML.php", async: false}).responseXML;

– xsldoc = $.ajax({ type: "GET", url: "clist.xsl", async: false}).responseXML;

– //XSLT transform using two DOMs – $('#ctable').transform({ xmlobj:xmldoc, xslobj:xsldoc});

46

Page 31: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Sorting & filtering• Web form controls are like this:

– <label for="sort-lname">Last Name</label> <input type="radio" name="sort"id="sort-lname" onclick="changeStyle();" />

– <label for="sort-asc">Ascending:</label><input type="radio" name="order"id="sort-asc" onclick="changeStyle();" />

– <textarea name="filter" rows="4" cols="14"></textarea>

– <input type="button" onclick="changeStyle()" value="Filter" />

47

Page 32: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Sorting

• Simple execution sequence:1. User changes an HTML control2. Event handler (JavaScript function) executes

• Alters XSL DOM <xsl:sort .../> element• Re-executes XSL transform

3. Control returns to the browser with updated HTML

48

Page 33: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Event handler codefunction changeStyle() {

//find the sort node in the XSL doc var sortNode=xsldoc.getElementsByTagName("xsl:sort")[0];

//hard-wired buttons determine the sort order: if (document.webform.sort[0].checked) { select="last_name"; //XSL attribute values datatype="text"; //depending on check box selections } else if //... etc, 1 else for each checkbox ...

if (document.webform.order[0].checked) order="ascending"; else order="descending";

//reset the XSL DOM sort node attributes sortNode.setAttribute("select", select); sortNode.setAttribute("data-type", datatype); sortNode.setAttribute("order", order);

//rerun the transform (using the two global XML DOMs) $('#ctable').transform({xmlobj:xmldoc,xslobj:xsldoc});

49

Page 34: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Event handler codefunction changeStyle() {... //insert XPath-style filter into the XSL parameter: var fstring = document.webform.filter.value; if (fstring=="") var filter = "//person"; //default else var filter = "//person[" + fstring + "]";

xsldoc.getElementsByTagName("xsl:param")[0] .setAttribute('select',filter);

...//rerun the transform (using the two global XML DOMs)

$('#ctable').transform({xmlobj:xmldoc,xslobj:xsldoc});

} //end of 50

Page 35: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

JSON

Finally....

(not examinable!)

51

Page 36: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

JSON• JSON (JavaScript Object Notation) is a lightweight data-interchange format.

– json.org• XML

– <persons> <person><first_name>James</first_name>...</person> ...</persons>

• JSON:– {

"persons": [ { "person": { "first_name":"James", ... } }, ... ]}

• Example URL (JSON)

52

Page 37: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Processing JSON

• Rather than XSL, must write JavaScript to process the JSON data• Sorting & filtering is harder

• Can still use innerHTML, $().html(...) etc. but now the HTML is generated as strings now by the XSL...

53

Page 38: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Processing JSONfunction processJSON(j) { var HTML = ''; var total = 0; //append the table rows full of data for (var i=0; i<j.persons.length; i++) {

HTML += '<tr><td>' + j.persons[i].person['date'] + '</td>'; HTML += '<td>' + j.persons[i].person['last_name'] + ... +

'</td>'; //etc... HTML += '<td>' + j.persons[i].person['amount'] + '</td>'; total += parseFloat(j.persons[i].person['amount']);

}

$('#ctable').html( '<table ...Total: ' + total + '...</tr>' + HTML);

} 54

Page 39: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Producing JSON server-side<?php//script to return data as JSON:header('Content-Type: application/json; charset=utf-8'); //As before: connect to DB, query data etc...//Write JSONecho '{"persons":['; $n = mysql_num_rows($data); for ($i=0;$i<$n;$i++) { $row=mysql_fetch_row($data); echo '{"person": {'; printf("\"first_name\":\"%s\",",

htmlspecialchars($row[0])); //etc for $row[1] to $row[7]... echo '}}' . (($i==$n-1)?'':','); } echo ']}';?>

55

Page 40: Dr James Denholm-Price j.denholm-price@kingston.ac.uk XP Lecture 9 WEB APP’S: WORKING WITH THE DOCUMENT OBJECT MODEL 1.

Summary• DOM specification is used to work with HTML and XML

documents• Components of document (elements, attributes, etc.) are

nodes• Element and attribute values can be modified• jQuery + Transform enables easy cross-browser development

56