i. defining web applications application... · 2018-04-04 · lecture 1 alex cummaudo hit3326 -...

39
Lecture 1 Alex Cummaudo HIT3326 - WAD 15/08/2013 I. Defining Web Applications Applications which run through a web browser - No need for extra software (except the browser) - Need a persistent internet connection though The internet protocol stack helps us achieve this (from logical to physical connection) - Web Apps sit at the top layer (Application) - HTTP: Active clients will send requests to passive servers who wait for requests Basic Web App Process 1. Client makes request to Web Server (which hosts the static pages) 2. Web Server sends back HTML pages 3. User interacts with their downloaded HTML Pages 4. The Web Server receives this request - a. Sends information to App Server - b. App server gets data from Database or APIs - c. May process data and render it's HTML (Synchronous) 5. Rendered page sent (Synchronous) or DOM updated (Asynchronous) Model View Controller Architecture The Controller decouples the Model and View and sits between the two Model Domain-specific representation of information Database (Raw) X M L , M y S Q L , JSON View Rendering of the model into a more suitable presentation UI HTML + CSS Controller Processes which respond to the view which may invoke change to the model Interaction PHP / ASP .NET or AJAX / 1 6

Upload: others

Post on 29-Mar-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Lecture 1 Alex Cummaudo HIT3326 - WAD 15/08/2013

I. Defining Web Applications▸ Applications which run through a web browser

- No need for extra software (except the browser)- Need a persistent internet connection though

▸ The internet protocol stack helps us achieve this (from logical to physical connection)- Web Apps sit at the top layer (Application)- HTTP: Active clients will send requests to passive servers who wait for requests

Basic Web App Process

� ▸ 1. Client makes request to Web Server (which hosts the static pages)▸ 2. Web Server sends back HTML pages▸ 3. User interacts with their downloaded HTML Pages▸ 4. The Web Server receives this request

- a. Sends information to App Server- b. App server gets data from Database or APIs- c. May process data and render it's HTML (Synchronous)

▸ 5. Rendered page sent (Synchronous) or DOM updated (Asynchronous)

Model View Controller Architecture

▸ The Controller decouples the Model and View and sits between the two

Model Domain-specific representation of information

Database(Raw)

X M L , M y S Q L , JSON

View Rendering of the model into a more suitable presentation

UI HTML + CSS

Controller Processes which respond to the view which may invoke change to the model

Interaction PHP / ASP .NET or AJAX

� / �1 6

Lecture 1 Alex Cummaudo HIT3326 - WAD 15/08/2013

Fat and Thin Clients ▸ Allocating how much processing power is given to the controller

- Fat Clients: Clients does most of the processing (AJAX); Servers mainly host data- Thin Clients: Server does most of the processing (PHP/ASP .NET etc.) and hosts

▸ How do we allocate processing power?- Capacity: Is the server always busy?- Bandwidth: Can we afford to transmit a lot of data constantly between clients/servers?▪ Do we send our entire data base to the client?

- Security: Can we minimise transmission over the insecure Internet?▪ Do we send our entire data base to the client?

- Complexity: Do we need lots of processing for something simple?▪ Do we send our entire data base to the client?

� / �2 6

Lecture 1 Alex Cummaudo HIT3326 - WAD 15/08/2013

II. The Two Web Application Models

1 - Classic Web Application Model ▸ Emphasis on a Thin Client / Server-Side Processing

- 1. Client enters input and now waits for response- 2. Sever uses client's input as parameters- 3. Server processes parameters- 4. Server sends response- 5. Client downloads a new page based on response

▸ It is a synchronous method:- The client needs to wait for the server response:▪ The View (UI) is unresponsive while the Model is being updated by the server

- The client cannot continue on with other tasks.- A new page is always sent back; dynamic page interaction- This leads to slow performance and limited interactivity, but is simpler ▪ The PHP is embedded into the HTML, but the Server processes it.

2 - Asynchronous JavaScript and XML (AJAX) ▸ Emphasis on a Fat(er) Client, where an AJAX engine sits on top of the client's HTML

- 1. Client enters input (a JavaScript call to event handler) and continues on doing other things

- 2. The AJAX engine uses event handlers to listen to these JavaScript calls sends the request using XMLHttpRequest Object

- 3. Server uses AJAX's input (from Client) as parameters- 4. Server sends a response (XML data)- 5. AJAX engine receives the response and parses the XML data as HTML- 6. AJAX engine updates the HTML page using DOM

▸ It is an asynchronous method:- The client does not need to wait▪ When a 'request' is sent, there is a JavaScript call to the AJAX engine▪ The AJAX engine that sits on top of the client's browser will use event handlers to

see if the user has clicked on items etc.▪ It is the event handlers which then send the actual HTTP request▹ This is all done in the background so the user doesn't need to wait

▪ Only partial updates to the page are updated; it is always the same page ▸ AJAX decouples the server and client interaction entirely

� / �3 6

Lecture 1 Alex Cummaudo HIT3326 - WAD 15/08/2013

What is AJAX? ▸ It is a JavaScript engine that uses the following technologies:

▸ The XMLHttpRequest allows us to send requests and retrieve responses in the background (i.e. it lives in the AJAX engine) --> this is why we don't need to wait!

▸ The AJAX engine uses the event handlers (which also live in the AJAX engine)

Technology Job Where? MVC?

XHTML + CSS Presentation Client View

DOM Altering PresentationAltering Data

ClientServer

Controller

XML or JSON or MySQL

Contains Data Server Model

XPATH Selects part of an XML document

Server Controller

XSLT Transforms XML to XHTML, CSV, TXT...

Client or Server Model

XMLHttpRequest Object

Communications link between client and sever

Client Controller

JavaScript Glues everyth ing together

Client Controller

PHP or ASP .NET S e r v e r - s i d e processing

Server Controller

� / �4 6

Lecture 1 Alex Cummaudo HIT3326 - WAD 15/08/2013

Visual Representation of Both Models: Both methods of HTTP Transport

Rendering Using Classic Model:

▸ User clicks on a button- The event-handler (attached to the button) makes a direct procedure call to the server- The client has to wait for for the event handler to:▪ transmit the parameters (HTTP request)▪ processing of server▪ transmission of result (HTTP response)

- The page refreshes to display the result

� / �5 6

Lecture 1 Alex Cummaudo HIT3326 - WAD 15/08/2013

Rendering Using AJAX Model:

▸ User clicks on a button- The event-handler (attached to the button) makes a request to the AJAX engine- We create an XHR object which will then handle for us:▪ The HTTP request▪ What to do when the server responds▹ Modify the DOM and therefore no page refresh

▪ The basic syntax:1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17

//! Create a new XHR object for all browsers + >IE7 var xhr = new XMLHttpRequest();

//! Open a new GET method with the URL; the true = asynch. method xhr.open("GET", "http://url/process.php?id=Alex", true);

//! Check if the state has changed xhr.onReadyStateChange = function() { //! If the server has finished processing? if (xhr.readyState == 4 && xhr.status == 200) {

//! Use DOM to change the page }

}

� / �6 6

Lecture 2 Alex Cummaudo HIT3324 - WAD Semester 2 2013’

I. Basic Syntax

Variables ▸ All variables start with a dollar sign ($), then a alphabetic character

- Auto-global variables use _ as their alphabetic character, e.g. _GET; (see later) - You must initialise as you declare.

▸ You can embed variables directly in strings, or concatenate them:

$name = "Fred";//! Embed a string directly in double quotesecho "Hello there $Fred! Have a nice day!";//! Alternatively concatenate with a commaecho "Hello there ", $Fred, "! Have a nice day!";//! However single quotes result in verbatimecho 'Hello there $Fred! Have a nice day!'

Global Variables ▸ If you declare a variable inside a function, it is a local variable ▸ If you want to declare a global variable inside a function, use the global keyword:

function eat_banana() { global $globVariable = 100; //!< Declares a global variable $locVariable = 10; //!< Declares a local variable}

Autoglobals ▸ A predefined associative array (uses keys) of common client/server/environment info

Constant ▸ Use define( ) function to create a constant: define("CONSTANT_NAME", value);▸ No dollar sign is required for defining a constant.

PHP1

Web Application Development, 2013Swinburne University of Technology 19

The global Keyword� With many programming languages, global variables are

automatically available to all parts of your program including functions.

� In PHP however, we need to use the global keyword to declare a global variable in a function where you would like to use it. <?phpfunction testScope() {

global $globalVariable;echo "<p>$globalVariable</p>";

}$globalVariable = "Global variable";testScope();

?>

� If no “global” above, an error message will be printed out. 37

Using Autoglobals� PHP includes various predefined global arrays, called

autoglobals or superglobals

� Autoglobals contain client, server, and environment information that you can use in your scripts

� Autoglobals are associative arrays – arrays whose elements are referred to with an alphanumeric key instead of an index number

See Predefined Variables, Superglobals and examples: http://php.net/manual/en/reserved.variables.php

38

PHP1

Web Application Development, 2013Swinburne University of Technology 20

PHP Autoglobals

39

Array Description$_GLOBALS An array of references to all variables that are defined with global scope$_GET An array of values from the submitted form with the GET method$_POST An array of values from the submitted form with the POST method$_COOKIE An array of values passed to HTTP cookies$_SESSION An array of session variables that are available to the current script$_SERVER An array of information about this script's web server$_FILES An array of information about uploaded files$_ENV An array of environment information$_REQUEST An array of all the elements found in the $_COOKIE, $_GET, and $_POST array

Using Autoglobals (continued)� Use the global keyword to declare a global variable within the

scope of a function� Use the $GLOBALS autoglobal to refer to the global version of

a variable from inside a function� $_GET is the default method for submitting a form� $_GET and $_POST allow you to access the values of forms

that are submitted to a PHP script� $_GET appends form data as one long string to the URL

specified by the action attribute� $_POST sends form data as a transmission separate from the

URL specified by the action attribute

40

� / �1 3

Lecture 2 Alex Cummaudo HIT3324 - WAD Semester 2 2013’

Data Types ▸ Primitive data types: Integer, Float, Bool, String, NULL.

- Use function getType( ) to get the type of a value▸ PHP is a loosely typed programming language

- The data type of a variable can be changed at runtime- Why? Interpreter in PHP (read as we go) vs., say, compiler (such as C) --> (fixed types)- As we parse the file, the type changes/is read every time it is read

▸ Resource data types: reference external files▸ Composite data types: arrays and objects

- Indexed arrays: use an index to reference values--> list (use index) --> order- Associative array: use a key to reference values --> set (use key) --> no order

Indexed:$array_name = array("One", "Two", "Three");Associative:$array_name[] = "Apple";$array_name[] = "Banana";$array_name[] = "Carrot";

- The array elements can be of different types. ▸ Can count elements in an array using count( ) function▸ Can print all elements in an array using print_r( ) function

Expressions Unary operator:

▸ One operand, e.g. !atSchool, count++

Unary Prefix increment operatorcount = 0;newCount = ++count; // assigns 1Unary Postfix increment operatorcount = 0;newCount = count++; // assigns 0

Conditional expressions:

? <expressionTrue> : <expressionFalse>;1 == 1 ? "Yes" : "No"; // Output is "Yes"

� / �2 3

Lecture 2 Alex Cummaudo HIT3324 - WAD Semester 2 2013’

Special operators:

Functions

function name_of_function(parameters) { ... }

▸ Use global variables any; local variables will work only in the function you declare

'Foreach as' Loop ▸ Loops through every element in an array

foreach ($array_name as $i) { ... }

PHP1

Web Application Development, 2013Swinburne University of Technology 13

Comparison Operators (continued)

25

PHP comparison operators

Conditional Operators� The conditional operator executes one of two expressions,

based on the results of a conditional expression

� The syntax for the conditional operator is:conditional expression

? expression1 : expression2;

� If the conditional expression evaluates to true, expression1 executes; otherwise, expression2 executes$blackjackPlayer1 = 20;($blackjackPlayer1 <= 21)

? $result = "Player 1 is still in the game."

: $result = "Player 1 is out of the action.";

/* $result will be assigned "Player 1 is still in the game."

26

PHP1

Web Application Development, 2013Swinburne University of Technology 14

Logical Operators� Logical operators are used for comparing two Boolean

operands for equality

� A Boolean value of true or false is returned after two operands are compared

PHP logical operators

27

Special OperatorsPHP special operators

Note: These Special Operators are introduced throughout this unit as necessary 28

� / �3 3

Lecture 3 Alex Cummaudo Web Application Development Semester 2 2013

I. Working With Forms▸ Checking fields using:

isset() is the variable initialised?empty() is the variable empty?is_numeric() is the variable numeric?

- Use the global variable (array) _GET or _POST to access the variables sent from a HTML form

▸ Sending an email:

mail( recipient(s), subject, message, [additional header] );$to = "[email protected]";$sub = "Happy fun slide";$message = "Cool beans";$headers = "From: Fred Smith <[email protected]>";mail ( $to, $sub, $message, $headers );

Strings ▸ String comparison functions

strcasecmp() //!< case insensitive comparison strcmp() //!< case sensitive comparison similar_text() //!< returns number of characters in common levenshtein() //!< returns number of characters you need to change for //!< the two strings to be the same strlen() //!< returns total number of characters in a stringstr_word_count() //!< returns word count strpos() //!< returns the pos of first occurrence of parameter strchr() //!< returns everything from first occurrence of substring strrchr() //!< same as above, but from reverse

- Add an i to make stuff case insentive, e.g. str_replace( ) and str_ireplace( )

▸ String replacement functions

str_replace(part_of_str_to_replace, replacement_str, full_str);Replaces part of a string with another stringsubstr_replace(string, replacement_string, start_position, [length]);Replaces everything in the string with

� / �1 5

Lecture 3 Alex Cummaudo Web Application Development Semester 2 2013

▸ String segmentation functions

strtok(string, token);Breaks a string (1by 1) into smaller strings, separated by a token (e.g. ,)e.g. $token = strtok("hello world. cool", ". "); while ($token != false) { echo "$token"; strtok(". "); }str_split(string, [length]);Splits a string into an array of char, or length of array of charsexplode(token, string); or implode(token, string_array);Divides/concatenates a string into an array of substrings, with each element separated by a token

▸ String concatenation

Standard: $str = "string ".$var." is cool";Assignment: $str .= "hey"; //!< Add to the $str

- Using a single-quote string, you will need \' to print an apostrophe- Conforms to C-style escape characters- Can put a value of variable inside a curly brackets to make it a complex string syntax

$veg = "carrot"echo "Do you have any $vegs" //!< ERROR: $vegs doesn't existecho "Do you have any {$veg}s" //!< Results in "Do you have any carrots"

II. Windows & UNIX directories▸ Use files or databases to permanently store data▸ UNIX Permissions: Lefthand access (most-private) should as

be greater than the right-hand side

PHP2

Web Application Development, 2013Swinburne University of Technology 11

How to Implement These Operations

21

<?phpif(isset($_GET['emailfield']) && isset($_GET['namefield'])) {

$email = $_GET['emailfield'];echo "<p> The email contains " . strlen($email) . " chars and " . str_word_count($email) . " words.</p>";$newName = $_GET['namefield'];$nameEnd = strpos($email, "@");echo "<p> The position of the @ in <em>$email</em> is $nameEnd.</p>";$name = substr($email, 0, $nameEnd);echo "<p> The name part before the @ is <em>$name.</em></p>"; $institute = substr($email, $nameEnd+1);echo "<p> The institute part after the @ is <em>$institute</em></p>";$instSegment = explode(".", $institute); $cnt = count($instSegment);echo "<p> The components of the institute include $cnt parts. They are:</p>"; for ($i=0; $i<$cnt; $i++) echo "<p><em>" . $instSegment[$i] . "</em></p>";echo "<p> Email for the new member is <em>". str_replace($name, $newName, $email). "</em></p>";echo "You need to change " . levenshtein($name, $newName) . " characters to make the new and the old

email addresses the same.</p>";}

?>

More String Functions� http://www.w3schools.com/php/php_ref_string.asp

� http://php.net/manual/en/ref.strings.php

22

PHP2

Web Application Development, 2013Swinburne University of Technology 12

Windows & Unix/Linux File and Directory� File is used to store data permanently for retrieval later

� May use different end of line ‘\r’ ‘\n’ characters

� Directory (in Unix/Linux), also referred to as a folder (in Windows) is a virtual container within an electronic file system

� Path delimiting character� Windows uses ‘\’, e.g. ‘hit3323\assign1’� Unix/Linux uses ‘/’, e.g. ‘hit3323/assign1’

� Unix/Linux has access permissions for directories/files, e.g. owner

group

others

rwxrwxr_x (‘0775’)23

PHP Directory Functions

24

PHP directory functions

� / �2 5

PHP2

Web Application Development, 2013Swinburne University of Technology 11

How to Implement These Operations

21

<?phpif(isset($_GET['emailfield']) && isset($_GET['namefield'])) {

$email = $_GET['emailfield'];echo "<p> The email contains " . strlen($email) . " chars and " . str_word_count($email) . " words.</p>";$newName = $_GET['namefield'];$nameEnd = strpos($email, "@");echo "<p> The position of the @ in <em>$email</em> is $nameEnd.</p>";$name = substr($email, 0, $nameEnd);echo "<p> The name part before the @ is <em>$name.</em></p>"; $institute = substr($email, $nameEnd+1);echo "<p> The institute part after the @ is <em>$institute</em></p>";$instSegment = explode(".", $institute); $cnt = count($instSegment);echo "<p> The components of the institute include $cnt parts. They are:</p>"; for ($i=0; $i<$cnt; $i++) echo "<p><em>" . $instSegment[$i] . "</em></p>";echo "<p> Email for the new member is <em>". str_replace($name, $newName, $email). "</em></p>";echo "You need to change " . levenshtein($name, $newName) . " characters to make the new and the old

email addresses the same.</p>";}

?>

More String Functions� http://www.w3schools.com/php/php_ref_string.asp

� http://php.net/manual/en/ref.strings.php

22

PHP2

Web Application Development, 2013Swinburne University of Technology 12

Windows & Unix/Linux File and Directory� File is used to store data permanently for retrieval later

� May use different end of line ‘\r’ ‘\n’ characters

� Directory (in Unix/Linux), also referred to as a folder (in Windows) is a virtual container within an electronic file system

� Path delimiting character� Windows uses ‘\’, e.g. ‘hit3323\assign1’� Unix/Linux uses ‘/’, e.g. ‘hit3323/assign1’

� Unix/Linux has access permissions for directories/files, e.g. owner

group

others

rwxrwxr_x (‘0775’)23

PHP Directory Functions

24

PHP directory functions

Lecture 3 Alex Cummaudo Web Application Development Semester 2 2013

mkdir(path, mode, [recursive], [context]);e.g. mkdir("lect2", 0755);readdir() //!< Returns a list of the file directoryscandir() //!< Makes an array indexed with the directory files

unlink() //!< Deletes a filermdir() //!< Deletes a directory

Three Stages of Reading a File ▸ ( 1 ) Open the file stream using fopen ( file, mode )

- Different modes allow us to do different things (e.g. read only at start)

- A file pointer is created to the return of fopen▪ Use the mode to tell us where the pointer is in the

file▪ A + in the mode means readwrite, while no +

means write only

▸ ( 2 ) Read data to a variable or write data to the file▸ ( 3 ) Close the file stream using fclose ( )

$file = fopen("file.txt", "a"); //!< Open using appendingflock($file, lock-op); //!< Lock (or unlock) file other accessfwrite($file, "string"); //!< Do stufffclose($file) //!< Close

▸ Alternatively, to completely write a whole new file (no open/close), use:

file_put_contents(filename, string, [option]); //! opt = FILE_APPEND etc.

PHP2

Web Application Development, 2013Swinburne University of Technology 13

Reading Directories� Open a handle to the directory with the opendir() function� To iterate through the entries in a directory, use the readdir()

function to return the file and directory names from the open directory� Use the closedir() function to close a directory handle

$dir = "../data";$dirOpen = opendir($dir);while ($curFile = readdir($dirOpen)) {

echo $curFile , "<br />";}closedir($dirOpen);

� Use the scandir() function to returns an indexed array containing the names of files and directories in the specified directory$dir = "../data"; $dirEntries = scandir($dir);foreach ($dirEntries as $entry) {

echo $entry , "<br />";}

25

Creating Directories� The mkdir() function creates a new directory. It returns tree

on success, or false on failure.mkdir(path, mode[, recursive, context]);

� On mercury, suppose the current directory is username/hit3323/www/htdoc. We create mkdir("Lec2", 0777);

mkdir("../data/assignment1", 02770);

Note: we need to change mode of username/hit3323/www/data…/www> chmod 02770 data

26

For mercury File Permissions, see: https://csg.ict.swin.edu.au/livecsg/help/Mercury_Web_Server

PHP2

Web Application Development, 2013Swinburne University of Technology 14

Obtaining File and Directory Information

27Returns the size of the file in bytesfilesize(filename)

Common file and directory information functions

PHP file and directory status functions

Copying, Renaming and Removing� Use the copy() function to copy a file with PHP, it returns true

if successful or false if notcopy(source, destination)

� Use the rename() function to rename a file or directory with PHP, it returns true if successful or false if not

rename(old_name, new_name)

� Use the unlink() function to delete a file and the rmdir() function to delete a directory, they return true if successful or false if not

� Use the file_exists() function to determine whether a file or directory name exists before you attempt to copy/rename/delete it

28

� / �3 5

PHP2

Web Application Development, 2013Swinburne University of Technology 15

Opening and Closing a File� A stream is a channel used for accessing a resource that you

can read from and write to� The input stream reads data from a resource (such as a file) � The output stream writes data to a resource� Usually a three stage process:

1. Open the file stream with the fopen() function2. Write data to or read data from the file stream3. Close the file stream with the fclose() function

29

Opening and Closing a File� A handle is a special type of variable that PHP uses to represent

a resource such as a file� The fopen() function opens a handle to a file stream

$open_file = fopen("text file", "mode");

� A file pointer is a special type of variable that refers to the currently selected line or character in a file

� Use the fclose() function when finished working with a file stream to save space in memory$bowlersFile = fopen("bowlers.txt", "a");

$newBowler = "Doe, John\n";

fwrite($bowlersFile, $newBowler);

fclose($bowlersFile);

30

PHP2

Web Application Development, 2013Swinburne University of Technology 16

Mode of fopen()

31

Mode parameter of the fopen() function

File Pointer$bowlersFile = fopen("bowlers.txt", "r+");

Location of the file pointer when the fopen() function uses mode “r+”

32

$bowlersFile = fopen("bowlers.txt", “a+");

Location of the file pointer when the fopen() function uses mode “a+”

Lecture 3 Alex Cummaudo Web Application Development Semester 2 2013

▸ You can use file ( ) to automatically read file contents into an indexed array, making elements at each \n or \r

▸ You can use file_get_contents ( ) to read contents of a file to a variable

III.Arrays

Start of Arrayarray_shift(); //!< Removearray_unshift(); //!< AddsEnd of Arrayarray_pop(); //!< Removearray_push(); //!< AddAt any part of arrayarray_splice($array, [element_to_start], [element_to_delete], [replace_w]);Merge Arraysarray_merge($array1, $array2); //!< Duplicate keys are overridden

▸ Associative arrays:- Rather than use indexes use keys

To set: $array = array (key => value); or $array["key"] = "value";To get: $array["key"];in_array() //!< returns true if value is in arrayarray_key_exists() //!< returns true if key is in arrayarray_search() //!< returns key/idx if value is in array

▸ 2D Arrays:- Just create one array within the other:

$categories = array ( array("Dog", "Cat", "Chicken"), array("Car", "Boat", "Plane"), array("Red", "White", "Blue"));

PHP2

Web Application Development, 2013Swinburne University of Technology 21

Reading an Entire File� The file_get_contents() function reads the contents

of a file into a string, e.g.,$sfWeather = file_get_contents("sfweather.txt");

� The readfile() function prints the contents of a file along with the file size to a Web browser

� The file() function reads the contents of a file into an indexed array. It automatically recognises whether the lines in a text file end in \n, \r, or \r\n

� The fread() function reads the contents of a file into a string up to a maximum number of bytes

41

Example of file() Function $january = "48, 42, 68\n"; $january .= "48, 42, 69\n";$january .= "49, 42, 69\n"; $january .= "49, 42, 61\n";$january .= "49, 42, 65\n"; $january .= "49, 42, 62\n";$january .= "49, 42, 62\n";file_put_contents("sfjanaverages.txt", $january);$januaryTemps = file("sfjanaverages.txt");for ($i=0; $i<count($januaryTemps); $i++) {

$curDay = explode(", ", $januaryTemps[$i]);echo "<p><strong>Day " . ($i + 1)

. "</strong><br/>";echo "High: {$curDay[0]}<br />";echo "Low: {$curDay[1]}<br />";echo "Mean: {$curDay[2]}</p>";

}

42

PHP2

Web Application Development, 2013Swinburne University of Technology 22

Reading Data Incrementally

43

PHP functions that iterate through a text file

Reading Data Incrementally� You must use fopen() and fclose() with the functions

listed in the table in the previous slide.� The commonly used fgets() function uses the file pointer to

iterate through a text file� Each time you call any of these functions, the file pointer

automatically moves to the next line in the text file (except for fgetc())

� Each time you call the fgetc() function, the file pointer moves to the next character in the file

� Often combined with the feof() function

44

� / �4 5

Lecture 3 Alex Cummaudo Web Application Development Semester 2 2013

� / �5 5

Lecture 4 Alex Cummaudo Unit Name 26/04/2016

I. MySQL + Mercury

Admin Stuff ▸ GRANT/REVOKE allows us to create/give away accounts and assign privileges

- You can assign custom privileges: SELECT, DROP TABLE, INSERT etc.

� ▸ You can delete users using DROP USER

Working With A Database

CREATE DATABASE <name> -- creates a databaseSHOW DATABASES -- shows all databases storedUSE DATABASE <name> -- start working with a databaseSELECT DATABASE <name> -- displays currently working databases

II. PHP + MySQL

1. Connection

// Connecting to a database$connection = mysqli_connect(<host>, [<user>, <password>, <database>]);// Selecting a database to work withmysqli_select_db(<connection>, <database in connection>);

▸ To select data, ensure you bulletproof - This means that we don't work with data that doesn't exist- To bullet proof a new connection, use an @:

$connection = @mysqli_connect(...)if (!connect) { /* didn't connect */ } else { /* connected & ready */ };

▸ Useful for debugging:

// Returns error descriptionmysqli_connect_error() o

MySQL

Web Application Development, 2013Swinburne University of Technology 10

Securing the Initial MySQL Accounts� Deleting the Anonymous User Account

mysql> DELETE FROM mysql.user WHERE User = '';

mysql> FLUSH PRIVILEGES;

� Assigning a Password to the Root Accountmysql> UPDATE mysql.user SET Password = PASSWORD('newpwd')

-> WHERE User = 'root';

mysql> FLUSH PRIVILEGES;

� The password assigned to the root account and other user accounts is case sensitive

19

Creating Users and Grant Privileges� Use a GRANT statement to create user accounts and assign

privileges

� Privileges are the operations that a user can perform with a database

� The GRANT statement creates the user account if it does not exist and assigns the specified privilegesGRANT privilege [(column)][, privilege [(columns)]]...

ON {table | * | *.* | database.*}

TO user [IDENTIFIED BY 'password'];

� If the user account already exists, the GRANT statement just updates the privileges

20

MySQL

Web Application Development, 2013Swinburne University of Technology 11

Common MySQL Database Privileges

21

Revoking Privileges and Deleting Users� You must be logged in with the root account or have sufficient

privileges to revoke privileges from another user accountREVOKE privilege [(column)][, privilege [(columns)]]...

ON {table | * | *.* | database.*}FROM user;

� The REVOKE ALL PRIVILEGES statement removes all privileges from a user account for a specified table or database

� Before deleting a user, you must first revoke all privileges assigned to the user account for all databases� Use the REVOKE ALL PRIVILEGES statement� View the privileges assigned to a user account with the SHOW GRANTS FOR user statement

� To delete an existing user, use the DROP USER userstatement to delete the account from the user table in the mysqldatabase

22

� / �1 2

Lecture 4 Alex Cummaudo Unit Name 26/04/2016

2. Manipulating ▸ For creating entries AND selecting entries:

mysqli_query(<connection>, <query>);//! Selecting Queriesmysqli_query($cn, "SELECT * FROM Postcode");//! Inserting Datamysqli_query($cn, "INSERT INTO Postcode(pcode, name) VALUES(3000, 'MEL')");mysqli_query($cn, "CREATE TABLE Message ( msg VARCHAR(25) )");//! Number of rows affectedmsqli_affected_rows(<connection>);

▸ You can embed PHP variables using the $ as per normal▸ Remember, SQL Strings need single quotes:

mysqli_query($cn, "SELECT name FROM Suburb WHERE classType = '$class');

▸ A query will always return a special result set type- Returns true if executing a command (e.g. CREATE TABLE <XYZ>)- Returns false if there are no results (e.g. failed query).- Returns a result set pointer to the selected database row for other events

▸ Use mysqli_fetch_row(<qry result set>) to return the attributes (cols) AS ARRAY Use mysqli_fetch_assoc(<qry result set>) to return attributes as ASSOCIATIVE ARRAY

$rowColumn = mysql_fetch_row($qry); or mysql_fetch_assoc($qry);echo "<table> <tr>";echo "<td> {$rowColumns[0] or $rowColumns['City']} </td>";echo "<td> {$rowColumns[1] or $rowColumns['Postcode']} </td>";echo "<td> {$rowColumns[2] or $rowColumns['Population']} </td>"; etc.

▸ Use mysqli_num_rows(<qry result set>) to return total number of rows in result set▸ Use mysqli_num_fields(<qry result set>) to return total number of fields in result set

1. Closing ▸ After we're finished manipulating, we close the database:

msqli_free_result(<result pointer>); // Free result pointers worked withmysql_close(<connection>); // Close the connection

� / �2 2

Lecture 5 Alex Cummaudo WAD - HIT3324 10/11/2013

I. User-Defined Objects

Creating User Defined Objects Constructor Functions

▸ By use of the keyword new ▸ Like defining a data type

- Useful for repetitive instances of the same class

var Car = function () { // New function assigned to var called car // Property, wheels this.wheels = 4; // Method, beep this.beep = function() { alert("Beep!"); }} var ford = new Car(); // New car objectford.beep(); // Call methods on objectford = null; // Destroy the car

Object Constructors ▸ Properties assigned after object created▸ Does not define a data type

- Useful for one-off instances only

var car = new Object(); // New generic objectcar.wheels = 4 // New property to new objectcar.beep = function() { alert("Beep!"); } // New method to new objectcar.beep(); // Calls the method defined up

Using Object Literals ▸ Similar to an object constructor, but everything is contained within one unit▸ Similar to a record/struct▸ Useful for one-off instances

// Notice the dot syntax; JSON notation!var car = { wheels: 4 beep: function() { alert("Beep!"); }}

� / �1 3

Lecture 5 Alex Cummaudo WAD - HIT3324 10/11/2013

Using an Object Prototype (Most Common!) ▸ Every object based off a prototype:

// Defining the prototype propertiesfunction car ( wheels ) { this.wheels = wheels;} // Defining the prototype methods directly on the prototypecar.prototype.beep = function() { alert("Beep!") }

II. DOM Basics▸ Everything in the DOM document is a node:

- The entire document is its own node: document node- Everything else is its own node:

� ▸ Note, we should use nodes and not Inner HTML to work with the DOM

- To create a node:▪ ( 1 ) Use document.createElement('<type>') and assign it to a var ▪ ( 2 ) Use document.createTextNode('<string>') to create the textual representation▪ ( 3 ) Append the text node as a child to the newly created element:

<var>.appendChild(<txtNode>)

▪ ( 4 ) Append the new element to an existing element, retrieved using getElementById <elementInDoc>.appendChild(<var>)

Step 1) var newElement = document.createElement('p');Step 2) var txtNode = document.createTextNode('Hey there!');Step 3) newElement.appendChild(txtNode);Step 4) var existingEl = document.getElementById('intro'); existingEl.appendChild(newElement);

JavaScript / DOM

22Web Application Development, 2013Swinburne University of Technology

43

DOM – Sample Code

// get list of all HTML body elements from document

var bodyels = document.getElementsByTagName("body");

// There is only one body element in a HTML 4.0 doc

// So bodyels will be a list with just one element

// We thus access the document body as follows

var docbody = bodyels.item(0);

// Set the CSS2 color property for the body to pink

docbody.style.color = "pink";

44

DOM Interfaces Everything in a document is a

node The entire document is a

document node - document Every HTML tag is an element

node The texts contained in the HTML

elements are text nodes Every HTML attribute is an

attribute node Comments are comment nodes

Element Type

NodeType

Element 1

Attribute 2

Text 3

Comment 8

Document 9

� / �2 3

Lecture 5 Alex Cummaudo WAD - HIT3324 10/11/2013

III.Event Handling▸ We can bind events, such as 'click' or 'onReadyStateChanged' (AJAX), to event handlers▸ The event handlers then handle what happens when the event occurs

Two Types of Event Models Event Bubbling

▸ Event bubbles outwards, from innermost element to outermost element- Event handlers for <p> determined- Event handlers for <div> then determined

<div> // --> Work up to here etc. <p> Click Me! </p> // START HERE ------>|</div> // --> Work up to here etc.

Event Capturing ▸ Reverse effect of bubbling▸ Event fires from outermost element in to innermost element

- Event handlers for <div> determined- Event handlers for <p> then determined

<div> // START HERE ----->| <p> Click Me! </p> //------> Work down to here</div> // START HERE ----->|

Registering Events

// Inline<a id="foo" onclick="doThis(); andThat();" />// W3C DOMvar element = document.getElementById('foo');element.attachEvent('onclick', doThis ); // NOTE!! No (); on doThiselement.attachEvent('onclick', andThat);element.detachEvent('onclick', andThat);// IE// Same as W3C but attachEvent = addEventListener detachEvent = removeEventListener

▸ To reference the element that caused the event:- e is it's name (W3C) or window.event (IE)- These are event objects; created when events occur and contain info about the event

� / �3 3

Lecture 6 Alex Cummaudo Web Application Development 07/11/2013

I. HTTP

Requests

<request-line><header(s)>blank line[<request-body>]GET Request - No BodyRequest Line: GET /books?name=Fred&publisher=Derf HTTP/1.1Headers : Host: www.banana.com User-agent: ... Connection: Keep-Aliveblank line :request body: POST Request - BodyRequest Line: POST /books HTTP/1.1 (no query string in URL)Headers : Host: www.banana.com User-agent: ... Connection: Keep-Alive Content-Length: 37 (need to know length)blank line :request body: name=Fred&publisher=Derf (query string goes in request body)

Responses

<status-line><headers>blank line[<request-body>]Response:Status Line: HTTP/1.1 200 OKHeaders : Date: Aug 20 2013 Content-Type: text/html Content-Length: 122blank line :resp. body : <html> <head> <title> Blah </title> </head> <body> <!--Content--> </body> </head>

� / �1 5

Lecture 6 Alex Cummaudo Web Application Development 07/11/2013

II. AJAX

The XHR Object ▸ The XHR Object is the key to communicating asynchronously▸ The readystatechange is an event; we attach an event-handler for this event each time the

readyState property changes- readyState properties are:▪ 0 - Uninitialised (haven't initialised a connection to any server yet)▪ 1 - Open (connection to server is open)▪ 2 - Sent (request has been sent to server)▪ 3 - Recieving (currently recieving a response)▪ 4 - loaded (recieved response data; all done!)

- status properties are the HTTP status; 200 (OK) 404 (Not found) etc.

Sending a Asynchronous Request ▸ 1 ) Create the XHR Object

var xhr = new XMLHttpRequest(); (if window.XMLHttpRequest) ORvar xhr = new ActiveXObject("Microsoft.XMLHTTP"); (MS CRAP!)

▸ 2 ) Create the request to the sever - The 'true' parameter means we want to communicate asynchronously and not synch.

xhr.open("GET/POST", "url.php[?queryString if GET]", [true/false]);

▸ 3 ) Create the event handler for readystatechange

xhr.onreadystatechange = handlerFunction;

- We create an event handler so that we can do other things in the meanwhile; so that the user isn't forced to wait for the processing of the server to finish up; no lag!

- It listens for any changes to readyState, it calls the event handler to make the changes!- Processing logic is non-linear over time; all of a sudden, everything is processed- Note: the readystatechange is called 4 times (from 1-4)▪ We only want changes to our HTML page on a successful change of state; check that

the readyState = 4 (data loaded) and the status = 200 (HTTP response says OK)

if ((xhr.readyState == 4) && (xhr.status == 200)) { /* Modify HTML! */ }

▸ 4 ) Send the request body once we've made our handler

xhr.send([null if GET/queryString if POST]);

� / �2 5

Lecture 6 Alex Cummaudo Web Application Development 07/11/2013

▸ There are some issues with IE (obviously!) — IE Aggressive Caching on GET- When sending GET requests, IE will automatically cache the results.- Stop this by adding the line after your connection is opened (or by using POST!):

xhr.open("GET", "file.php?queryString", true);xhr.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");

III.XML - Extensible Markup Language▸ XML is a meta-language: we write all the elements ourselves▸ It provides semantics for apps to communicate in a systematic fashion with the same set

of abstract data; the data (model) is not tied to a particular view

Basic Semantics

<boundary>...</boundary> // Boundaries contain nodes<role1>...</role1> // Roles exist for containing diff. sets of data<role2>...</role2><position> <position2 /> // Position 2 logically follows Position 1</position> // E.g., class -> student<container> <containment /> // Containers have nodes contained by boundaries<container>

▸ Well formed XML is compulsory when interacting between apps;- This allows each app to know how to parse through your XML- The structure must be well formed▪ Root class, start/end tags, empty self-contained elements have />, elements must

nest not overlap, attributes in quotes, markup characters used are entity refs, cannot use same name for >=2 attributes of same element, elements = _:, then _:-;

▸ Valid XML means that the data your XML contains makes sense:- Apps don't care if your data is actually correct; they just render it for you- The data can be validated (it's optional) using DTDs, XMLSchemas etc.

PCDATA vs. CDATA ▸ PCDATA is Parsed Character Data; i.e. the parse will parse through this data

- If you had semantical symbols such as < or &, the parser gets confused- Use entity references to get around this: &lt; == '<'

▸ CDATA is Character Data; it is not parsed by the parser as it may confuse the parser:

<![CDATA[ <html><body></body></html> <--- This may confuse poor old parser! :(]]>

� / �3 5

Lecture 6 Alex Cummaudo Web Application Development 07/11/2013

▸ Processing Instructions (PI) are hints to the parser to do particular things at that point

<?xml-stylesheet href='style.css' type='text/css'?> // Include a stylesheet

- The prolog is a PI:▪ XML declaration (version of XML used)▪ DTD for 'validating' your data:

<?xml version=1.0 encoding='UTF-8'?><!DOCTYPE book SYSTEM "book.dtd">

IV.XML+AJAX = Fun!▸ XHR objects can communicate well-formed XML from the server: the responseXML prop.▸ The XML can the be accessed, manipulated and queried using DOM Commands in JS

- The same can be done in PHP using XLST▸ By copying the XML contents into a JavaScript variable, we can manipulate it beforehand

before handing it over to HTML

var xhr = new [XMLHttpRequest()/ActiveXObject('Microsoft.XMLHttp')]; xhr = createRequest(); // Create the request firstif (xhr.overrideMimeType) { xhr.overrideMimeType("text/xml"); // Override MIME data to XML} xhr.open("GET", "xmlDocument.xml", true);// Get contents of my XML docxhr.onreadystatechange = function() { // Event handler function: if ((xhr.readyState==4) && (xhr.status == 200) { var xmlDoc = xhr.responseXML; // Make xmlDoc the response in XML parseThrough(xmlDoc); }} xhr.send(null);

▸ Then, we can use the xmlDoc variable we had above to parse through it, and create new elements in the XHTML document:

parseThrough(xml) { var data = xml.getElementByTagName('fruits'); for (fruit in fruits) { // New element p for each fruit var newEl = document.createElement('p'); // New text node for each new p, whose value is the fruit's text var newTx = document.createTextNode(fruit.textContent); // Append to XHTML Document newEl.appendChild(newTx); document.getElementById('id').appendChild(newEl); }}

� / �4 5

Lecture 6 Alex Cummaudo Web Application Development 07/11/2013

▸ We can also parse through it in PHP:

$xml = DOMDocument::load("xmlDocument.xml");$fruits = $xml->getElementsByTagName('fruits');foreach ($fruits as $fruit) { // An immediate node @ 0 references the textual node $txt = $fruit->item(0)->nodeValue; echo "<p> $txt </p>";}

▸ Other XML/PHP Methods include:

DOMDocument::load("filename.xml"); // Loads XML from fileDOMDocument::loadXML(string); // Loads XML from stringDOMDocument::save(); // Dumps an internal XML tree to a docDOMDocument::saveXML(); // Dumps an internal XML tree to a str

� / �5 5

Lecture 7 Alex Cummaudo HIT3213 Web Application Development 07/11/2013

I. Summary of XHR Comms▸ Benefits of XML + AJAX:

- XML can be used and manipulated on a server with the DOM API- PHP can process XML data on server- We send the response back asynch.- We process that response on the client

1. Submitting Data To The Server ▸ Open the communication using the open method on the XHR object

xhr.open([GET/POST], URL, [asynch (true) /synch (false)]);xhr.send(null); // Null if GETxhr.send(args); // Make some args if POSTvar args = "value=";args += data;

▸ Specify the event handler function that will execute when the client has received data from server

▸ Send the actual request to activate the communication

2. Server Receives the data, and processes it ▸ Can create XML documents and read existing XML documents

- We create using an XML DOM Object in PHP- We then load an XML document in using load( ); - We then manipulate by reading/updating nodes by the XML DOM- We then save an XML document—save( );—or serialise it to a string—saveXML( );

▸ Use PHP echo to echo the HTML response

3. Construct/Write the HTTP Response in XML ▸ We echo the string of the XML document to the client

- A HTTP response must be a string; we cannot send an XML object!

4. Receiving Data From The Server ▸ The XHR object receives the HTTP response echoed from the server▸ The event handler function will process the response:

if ((readyState == 4) && (status == 4)) { /* do stuff */ }

▸ Use XHR's responseText( ); or responseXML( ); to read the response as a string or XML- responseText( ); is used to receive textual data, JSON, HTML documents- responseXML( ); usually used for XML documents only

� / �1 3

Lecture 7 Alex Cummaudo HIT3213 Web Application Development 07/11/2013

IE ISSUES: using responseXML ▸ Specifiy the content type:

PHP:header("Content-type: text/xml");JS:xhr.overrideMimeType("text/xml");

5. Fetching XML Data from responseXML ▸ Use DOM API in JS to access the nodes:

var myCart = xhr.responseXML;var books = myCart.getElementsByTagName("book");var title1 = books[0].nodeValue;

II. State Information▸ HTTP is a stateless protocol—browsers don't have any persistent data about web pages ▸ Information that we need to keep across time is called state information ▸ Thus, we need to maintain the state of our persistent information

- A user makes a shopping cart in one session- If the user logs out, their shopping cart will be killed- We shouldn't need to store this in a database; it is good enough to store on clients- Other uses: counters for that particular user, user ids and passwords etc.

Using Cookies ▸ A small piece on information that is stored on the client, but maintained by the server▸ Two types:

- temporary: used within a single session- persistent: available beyond the session the cookie was created in

To Set

setcookie (key, value, [expires, path, domain, secure]);

▸ A path can allow for structure—"/marketing/" cookies, "/shoppingcart/" cookies etc.A domain can allow multiple servers to use this cookieA secure cookie can only be sent using HTTPS

To Read ▸ Auto-global variables: $_COOKIE['key'] is an associative array to access key/value pairs▸ New cookies only available after webpage is reloaded

� / �2 3

Lecture 7 Alex Cummaudo HIT3213 Web Application Development 07/11/2013

▸ A cookie itself can be an array on its own accord:

setcookie("cart[0]", "Apple");setcookie("cart[1]", "Banana");setcookie("cart[2]", "Carrot");

To Delete ▸ Simply set the time so it expires immediately (expires in the past):

setcookie (cart[0], "Apple", time()-100);

Sessions ▸ Sessions generate a unique Session ID even when the client disables cookies in the

browsers▸ This is an alternative to cookies▸ We can retireve the current user's session using the session_id( ); method

To Start A Session

session_start();

- This will generate a new session ID for us- It creates a text file on the Web server, saved in the directory as per my php.ini file.- The second time, we only retreive sessions from the session ID file- PHPSESSID is a query string used to pass the session ID between pages (old browsers)Using a Session

▸ The auto-global $_SESSION can be used to make session variablesDeleting a Session

session_destroy();

Use the values of the sessions and then destroy (old browsers)

Ajax Server Side Technologies

Swinburne University of Technology 21Web Application Development, 2013Swinburne University of Technology

Deleting a Session Use the session_destroy() function to destroy all data

registered to a session<?php

session_start();// this has to be called

$_SESSION = array();// unset all session variables

// Delete the session cookie if used

if (ini_get("session.use_cookies")) {

$params = session_get_cookie_params();

setcookie(session_name(), '', time() - 42000,

$params["path"], $params["domain"], $params["secure"] );

}

session_destroy();

?>

41

42

Shopping Cart Example Create a dummy catalogue page for a book seller using a

shopping cart (the book seller sells just ONE book, for now) Allow users to place items in the shopping cart Allow users to update the shopping cart without the need to

refresh the page (buy additional; remove all) Assume the user has been identified The shopping cart has three simple functions

Can add new items to it The quantity will increase by one if a second item is added Can remove all items from it

� / �3 3

Lecture 8 Alex Cummaudo HIT3324 - WAD 23/10/2013

I. XSL - eXtensible Stylesheet Language▸ 3 primary components:

- XSL-FO (XSL Formatting Objects)—used to actually implement the page- XPath—used to transverse through an XML document and locate objects- XSLT (XSL Transformer)—used to transform an XML document to other formats using

an XSL stylesheetXSLT

▸ An XSLT stylesheet allows us to transform the contents of an XML document into another format.

▸ It is in itself an XML document▸ It requires XPath to select data objects and transform them ▸ It's a declarative language—not procedural (step by step); it is

purely data-oriented

So how does it compare to DOM? DOM is direct manipulation to the view (directly modify the HTML)XSLT allows us to create as many new views from the XML as needed via XSL S/S

Using XSLT in AJAX ▸ We can use AJAX to help us with the XSLT processing part into a HTML document

- Client-side processing involves loading in an XML document, creating an XSLT Processor object and then transforming the XML using that processor, with the results places in some element

- Server-side is essentially the same

� / �1 6

Lecture 8 Alex Cummaudo HIT3324 - WAD 23/10/2013

Client-side XSLT using JavaScript

Server-side XSLT using PHP

▸ Essentially six steps:- 1 ) Create an XML Object and load in your XML file- 2 ) Create an XML Object and load in your XSL file- 3 ) Create your XSLT processor- 4 ) Import the XSL DOM Object in your XSLT processor- 5 ) Process the XML DOM Object with your XSLT processor- 6 ) Append your results to your page▪ Client-side: Append the XML to a new child▪ Server-side: Echo the response back in the HTTP request and append that XML to a child somewhere

123456789

10111213141516171819

// 1. Load in the XML file to a new XML Object var xmlObj = document.implementation.createDocument("", "doc", null); xmlObj.load("xmlFile.xml");

// 2. Load in the XSL file to a new XSL Object var xslObj = document.implementation.createDocument("", "doc", null); xslObj.load("xslFile.xsl");

// 3. Create the XSLT processor var xsltParser = new XSLTProcessor();

// 4. Load in the XSL file to parse with xsltParser.importStyleSheet(xslObj);

// 5. Process the xmlObj with the xslObj using the xsltParser var results = xsltParser.transformToFragment(xmlObj, document);

// 6. Append results somewhere in DOM document.getElementById("somewhere").appendChild(results);

123456789

10111213141516171819

// 1. Load in the XML file to a new XML Object $xmlObj = new DOMDocument('1.0'); $xmlObj->load("xmlFile.xml");

// 2. Load in the XSL file to a new XSL Object $xslObj = new DOMDocument('1.0'); $xslObj->load("xslFile.xsl");

// 3. Create the XSLT processor $xsltParser = new XSLTProcessor;

// 4. Load in the XSL file to parse with $xsltParser->importStyleSheet($xslObj);

// 5. Process the xmlObj with the xslObj using the xsltParser $results = $xsltParser->transformToXML($xmlObj);

// 6. Echo results in HTTP response echo $results;

� / �2 6

Lecture 8 Alex Cummaudo HIT3324 - WAD 23/10/2013

II. XPath▸ XPath is the technology that allows for transversal through the XML document

- A path is used to locate specific object/data in the XML when parsing it with a XSLT processor

- Similar in syntax to the UNIX file directory- An XPath data model (tree) is dynamically generated by the parser

▸ Location Path—the path of a object/data which is to be operated on- Relative to a context node- Absolute to the root note ( / )

▸ How does it work?- Start at a context node

Examples of different context nodes to start at...hotelsbooks/ (root)

- From the context node, we can take several directories down the tree:▪ Each path we take is known as a different axis ▹ Parent axis, self axis, child axis, descendent (n-child) axis, ancestor (n-parent) axis

▪ Each location step ( a / ) will take us to a new axis on the tree

Examples of different axes taken... (context node is books)books/book/authors/author/name[@first] (@ means attributes)books/book/authors/author/agebooks/book/publisher/location/citybooks/book/publisher/name* (* means all)

- A node test helps us work out if that node is applicable or not

XSLT and XPath

15Web Application Development, 2013Swinburne University of Technology

29

Predicates Predicates filter the returned nodeset Predicates are presented in square brackets, e.g.,

[attribute::star=“5”] [child::price < 150]

Predicates consist of expressions built from XPath functions There are four main categories of XPath functions for use in

predicates:1. Nodeset functions2. Boolean functions3. Number functions4. String functions

30

Abbreviated Location StepsAxis Abbreviation Unabbreviated equivalentChild hotel child::hotel

* child::**/price child::*/child::pricehotel[last()] child::hotel[last()]

Self . self::node()Parent .. parent::node()Attribute @star attribute::star

@* attribute::*descendant-or-self

.//city self::node()/descendant-or-self ::node()/child::city

hotels//name child::hotels/descendant::name

� / �3 6

Lecture 8 Alex Cummaudo HIT3324 - WAD 23/10/2013

▸ Predicates can help return a filtered set of nodes (nodeset)

All authors of book whose last name is Smith:books/book/authors/author/name[last="Smith"]All publishers in New York:books/book/publishers/location[city="New York"]All descendants (n-th childs) whose cost > 10books//book[cost > 10] e.g. books/book/retail[cost > 10] books/book/manufacture[cost > 10] books/book/purchase[cost > 10]The last book written by John Smithbooks/book[position() = last()]/author/name[first="John" last="Smith"]

III.Operating with XSLT + XPath

Constructing a Stylesheet ▸ After XML declared (XSL is an XML remember!) we declare that this XML is an XSL:

<xsl:stylesheet version="1.0" xmlns:xml="http://www.w3.org/1999/XSL/Transform">

Define the output type of the XSLT Transformation

<xsl:output method="html" version="5.0">

Define template for context element ▸ How should I style this context element?

- Usually everything will go in here, where our context element is the root element

<xsl:template match="context-el"> ... </xsl:template>

- However, we can use templates to apply the same set of XSL rules elsewhere:

<xsl:template match="//books"> <xsl:apply-templates/> Apply all future templates to...</xsl:template><xsl:template match="cost"> all cost descendants $<xsl:value-of select="./"> i.e. value of self cost element</xsl:template>I: 129.29, 11.11, 0.99; O: $129.29, $11.11, $0.99

� / �4 6

Lecture 8 Alex Cummaudo HIT3324 - WAD 23/10/2013

Processing ▸ Getting node text:

<p> Authors: <xsl:value-of select="./book/authors[1]" /> </p>

▸ Looping through nodes in a common nodeset:- Notice the change of context node once we're in the loop: from ./book, we go down one

in the XSLT tree and now we can just use ./title instead of ./book/title

<div class="books"> <h1> Books </h1> <xsl:for-each select="./book"> <p> Title: <xsl:value-of select="./title" /> </p> </xsl:for-each></div>

▸ Conditionals- If Test Is True: If and only if

<xsl:if test="count(./authors) > 1"> et. al.</xsl:if>

- Choose When Test/Otherwise: Perform this every time this is the case in a group of nodes, else do that...

<xsl:choose> <xsl:when test="./cost < 12.5"> <p> Going for a cheap price! </p> </xsl:when> <xsl:otherwise> <p> A bit pricey </p> </xsl:otherwise></xsl:choose>

▸ Sorting: Sort Select Order

<xsl:sort select="./authors/author/name[@last]" order="ascending" />

▸ Literals- Use curly braces to literally insert text of the item into this field, not reference it:- This would insert, say, the referencing value of the book's isbn (1020302010102)

<a href="#{./book/isbn}">

� / �5 6

Lecture 8 Alex Cummaudo HIT3324 - WAD 23/10/2013

▸ Creating XSL elements (used when parsing XML->XML)

Use:<xsl:element name="name"> {subelements/attributes} </xsl:element><xsl:attribute name="name"> value </xsl:attribute>E.g.:<xsl:element name="book"> <xsl:attribute name="genre"> romantic </xsl:attribute></xsl:element>would become:<book genre="romantic"/>

▸ XSLT variables (think as a pointer)- Write once- Read only henceforth (use $dollar to reference)

<xsl:variable name="first-book-title" select="./books[1]/title">...<xsl:value-of select="$first-book-title" />

� / �6 6

Lecture 10 Alex Cummaudo Web Application Development 23/10/2013

I. JSON - JavaScript Object Notation▸ Useful for transmitting data to and from Clients and Servers

- An nicer, more minimal way to XML▸ Two primary structures:

- Unordered key/value pairs- Ordered lists of values (like arrays)

▸ Datatypes:- Double-Quoted Strings - Numbers- Booleans- NULL- Objects—a subset collection of Key/Value pairs- Arrays—simple list of values

{ "Name" : "Fred" , "Age" : 25 , "Happy" : true , "Address" : { "Home" : "123 Fake Street" , "City" : "Fakeville" , "Postcode" : 3083 , } , "Units" : ["WAD", "DAD", "CompSys"] , always a comma}

▸ We access each member using dot notation:

JSONObject.Name == FredJSONObject.Address.Home == 123 Fake Street (an Object type)JSONObject.Units[2] == CompSys (an Array type)

▸ To convert between a JSON String Representations and JavaScript Objects, we can use:- eval( <string> ) — JSON String to JavaScript Obj- parseJSON( ) — JSON String to JavaScript Obj (Safer)- toJSONString( ) — JavaScript Obj to JSON String

var JSONString = xhr.responseText(); just get as standard XHR resp.var JS-Object = eval("("+JSONString+")"); note the redundant bracketsvar JS-Object = JSONString.parseJSON(); much cleaner way to use itvar JSONString = JS-Object.toJSONString();

� / �1 2

Lecture 10 Alex Cummaudo Web Application Development 23/10/2013

II. Using JSON Programatically

In JavaScript ▸ We can open JSON as simple .txt strings:

- Opening a new XHR as just a txt will automatically insert it in its xhrResponse

▪ XHR reads in the file as plain text; will not ensure for valid JSON :(

xhr.open("GET", "myJSONFile.txt", true); Content type is "text/plain"

- We contrast this to XML files that are opened with XHR, whereby XHR knows that is has loaded smart XML!▪ XHR will automatically ensure for valid XML : )

xhr.open("GET", "myXMLFile.xml", true); Content type is "application/xml"

In PHP ▸ No standard JSON libraries exist in PHP:

require_once('JSON.php'); Load in the library$jsonObj = new Services_JSON(); Create a new JSON service handlerArray -> JSON$someArray = array(123, 456, 789);echo $jsonObj->encode($someArray); Echoes a JSON Object as String

III.jQuery and AJAX▸ We can send AJAX requests far easier using the jQuery Framework

$.ajax({ type : "POST" , url : "source.php" , data : "name="+name , success : function() { doThis(); } });

� / �2 2

Lecture 1 Alex Cummaudo WAD 23/10/2013

I. Web Services▸ Where server-side functionality is provided by someone else ▸ There are three levels of systems that need to be considered:

� ▸ Interaction between our server and third party servers causes issues:

- XMLHTTPRequest objects will communicate with our servers fine- It is when it interacts with another domain and letting 3rd party data on the client where

there are issues

Web Service Characteristics ▸ Solutions provided by a common collaborative architecture▸ Provide building blocks that are not platform/language-specific▸ Accessible over common, internet protocols (below)▸ Provide a push toward service-oriented computing ▸ Simple software objects/components that will execute when called upon the API▸ Can be interfaced with from any other program▸ Is a locatable, registered service on a Web Service Registry—UDDI ▸ Loosely coupled connections between systems▸ Promote common functions that developers can consume

Technologic Characteristics ▸ SOAP (Simple Object Access Protocol)

- Network, Transport and Programming-Neutral Protocol- Allows a client to call a remote service- Formatted in XML

▸ WSDL (Web Services Description Language) - Provides the interface with how to interact (interface) with the service—think .h file- Formatted in XML

▸ UDDI (Universal Description, Discovery, and Integration) - How we can keep a Web Service Registry- A client-side API and SOAP-based server implementation- To store and retrieve information on service providers

Services on third party servers

Services on our own servers UI to the clients

� / �1 4

Lecture 1 Alex Cummaudo WAD 23/10/2013

Four Step Process of Web Services ▸ 1 ) Client calls the service over a protocol—HTTP▸ 2 ) Client selects a method of transmission to the server—HTTP-GET, HTTP-POST, SOAP▸ 3 ) Sever returns a value, in XML or JSON format▸ 4 ) Client acts upon this returned value

Transmission Approaches SOAP

▸ SOAP can be used to transmit a request/response to and from a service to a owned server▸ We create an XML document, with SOAP elements, and package its content:

<SOAP:Envelope> <SOAP:Header> ... </SOAP:Header> <SOAP:Body> ... </SOAP:Body></SOAP:Envelope>

REST - REpresentational State Transfer ▸ Focuses on a system's resources and states

- Use HTTP methods explicitly.- Be stateless.- Expose directory structure-like URIs.- Transfer XML, JavaScript Object Notation (JSON), or both.

▸ Exactly how we've been sending requests to the server this whole time:- Pros:▪ Response can be stored in XML▪ Uses HTTP (GET, POST) to transfer, ▪ Uses URIs for identification,▪ Can use HTTP authentication for security,

� / �2 4

Lecture 1 Alex Cummaudo WAD 23/10/2013

▪ Easy to use (with AJAX).- Con: not as secure as SOAPPROBLEM #1 — Same Origin Policy

▸ REST encounters the Same Origin Policy where:- Attempting to use a Web Service's endpoint as the location used in an XHR request

object will not work▪ It is a WWW restriction that:

Clients can only directly access resources from the same domain it has loaded- XHR ensures that the request to another page is located on the same domain as the

requester

� Same Origin Proxy:

Clients connected to xyz.com will only be able to send XHR requests to xyz.com

▸ Solution: Application Proxy - Just make the Web App Server talk to the Web Service; the Client will never know:▪ We create a proxy page on the Web Server to talk to the Web Service :D

- This is known as an Application Proxy

▪ We get the server to go off and do the external stuff for us!

� Resolving Same Origin Proxy:

Ask the server to access the external stuff we can't get and retrieve it for us!

� / �3 4

Lecture 1 Alex Cummaudo WAD 23/10/2013

PROBLEM #2 — Firewalls ▸ Invoking an AJAX request to a server ≠ getting through the corporate firewall▸ The only way you'll get through is invoking the request on a firewall proxy serve

� ▸ To resolve this, we can use cURL in our Web App's PHP:

$cURL = curl_init();curl_setopt($cURL, CURLOPT_URL, "abc.com"); a new cURL to abc.comcurl_setopt($cURL, CURLOPT_PROXY, "proxy.abc.com:8000"); use this proxyecho curl_exec($cURL); echo the response from the web service via proxy

II. APIs▸ APIs are similar to web services BUT:

- They are proprietary (don't have to be a registered, freely used service)▪ Proprietary == WE OWN THIS API!▪ Service == Freely to use by anyone

- Don't need to comply with SOAP/REST standards ▸ Just just a Web Service, provides:

- New set of methods, properties and objects at our disposal- New functionality made by a third party that we can work with- So we don't have to do all the work ourselves

▸ E.g. Google Maps

� / �4 4