Chapter 2: Interactive Web Applications



Similar documents
Chapter 2: Interactive Web Applications

WEB DEVELOPMENT COURSE (PHP/ MYSQL)

Chapter 3: Web Paradigms and Interactivity

DIPLOMA IN WEBDEVELOPMENT

Example. Represent this as XML

Certified PHP/MySQL Web Developer Course

Facebook Twitter YouTube Google Plus Website

Online Multimedia Winter semester 2015/16

General principles and architecture of Adlib and Adlib API. Petra Otten Manager Customer Support

UQC103S1 UFCE Systems Development. uqc103s/ufce PHP-mySQL 1

Visualizing a Neo4j Graph Database with KeyLines

Developing ASP.NET MVC 4 Web Applications MOC 20486

Mobile Web Design with HTML5, CSS3, JavaScript and JQuery Mobile Training BSP-2256 Length: 5 days Price: $ 2,895.00

Web Development using PHP (WD_PHP) Duration 1.5 months

Developing ASP.NET MVC 4 Web Applications

COURSE CONTENT FOR WINTER TRAINING ON Web Development using PHP & MySql

XML Processing and Web Services. Chapter 17

Visualizing an OrientDB Graph Database with KeyLines

CSCI-UA: Database Design & Web Implementation. Professor Evan Sandhaus sandhaus@cs.nyu.edu evan@nytimes.com

Course Outline Basic Web Development

LabVIEW Internet Toolkit User Guide

jquery Tutorial for Beginners: Nothing But the Goods

Multimedia im Netz Online Multimedia Winter semester 2015/16. Tutorial 03 Major Subject

Team Members: Christopher Copper Philip Eittreim Jeremiah Jekich Andrew Reisdorph. Client: Brian Krzys

NoSQL, But Even Less Security Bryan Sullivan, Senior Security Researcher, Adobe Secure Software Engineering Team

Developing ASP.NET MVC 4 Web Applications Course 20486A; 5 Days, Instructor-led

INFORMATION BROCHURE Certificate Course in Web Design Using PHP/MySQL

ANDROID APPS DEVELOPMENT FOR MOBILE GAME

Portals and Hosted Files

J j enterpririse. Oracle Application Express 3. Develop Native Oracle database-centric web applications quickly and easily with Oracle APEX

Facebook Twitter YouTube Google Plus Website . o Zooming and Panning. Panel. 3D commands. o Working with Canvas

The purpose of jquery is to make it much easier to use JavaScript on your website.

CSCC09F Programming on the Web. Mongo DB

International Journal of Engineering Technology, Management and Applied Sciences. November 2014, Volume 2 Issue 6, ISSN

Session D15 Simple Visualization of your TimeSeries Data. Shawn Moe IBM

This course provides students with the knowledge and skills to develop ASP.NET MVC 4 web applications.

Web Development. Owen Sacco. ICS2205/ICS2230 Web Intelligence

Real SQL Programming 1

ONLINE SCHEDULING FOR THE PRIVATE CLINIC "OUR DOCTOR" BASED ON WEB 2.0 TECHNOLOGIES

Introduction to web development and JavaScript

Art of Code Front-end Web Development Training Program

Introduction to Server-Side Programming. Charles Liu

Performance Testing for Ajax Applications

COURSE SYLLABUS EDG 6931: Designing Integrated Media Environments 2 Educational Technology Program University of Florida

Abstract. Description

ERIE COMMUNITY COLLEGE COURSE OUTLINE A. COURSE TITLE: CS WEB DEVELOPMENT AND PROGRAMMING FUNDAMENTALS

Connecting to a Database Using PHP. Prof. Jim Whitehead CMPS 183, Spring 2006 May 15, 2006

Advantage of Jquery: T his file is downloaded from

MyOra 3.0. User Guide. SQL Tool for Oracle. Jayam Systems, LLC

Intro to Web Programming. using PHP, HTTP, CSS, and Javascript Layton Smith CSE 4000

Software Requirements Specification For Real Estate Web Site

OIT 307/ OIT 218: Web Programming

Modern Web Development From Angle Brackets to Web Sockets

Application layer Web 2.0

Designing and Implementing an Online Bookstore Website

The full setup includes the server itself, the server control panel, Firebird Database Server, and three sample applications with source code.

Skills for Employment Investment Project (SEIP)

Perl & NoSQL Focus on MongoDB. Jean-Marie Gouarné jmgdoc@cpan.org

Introduction to D3.js Interactive Data Visualization in the Web Browser

Short notes on webpage programming languages

IT3503 Web Development Techniques (Optional)

Chapter 2: Interactive Web Applications

Advanced Web Development SCOPE OF WEB DEVELOPMENT INDUSTRY

CSCI110: Examination information.

CSCI110 Exercise 4: Database - MySQL

Sisense. Product Highlights.

NoSQL replacement for SQLite (for Beatstream) Antti-Jussi Kovalainen Seminar OHJ-1860: NoSQL databases

Other Language Types CMSC 330: Organization of Programming Languages

1. Introduction. 2. Web Application. 3. Components. 4. Common Vulnerabilities. 5. Improving security in Web applications

LAMP [Linux. Apache. MySQL. PHP] Industrial Implementations Module Description

Cyber Security Challenge Australia 2014

10CS73:Web Programming

How To Write A Web Server In Javascript

Developing a Web Server Platform with SAPI Support for AJAX RPC using JSON

Learning Web App Development

Programming in HTML5 with JavaScript and CSS3

DiskPulse DISK CHANGE MONITOR

Example for Using the PrestaShop Web Service : CRUD

Project 2: Web Security Pitfalls

Course Number: IAC-SOFT-WDAD Web Design and Application Development

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

IT3504: Web Development Techniques (Optional)

A Web- based Approach to Music Library Management. Jason Young California Polytechnic State University, San Luis Obispo June 3, 2012

Computer Science Course Descriptions Page 1

It is highly recommended that you are familiar with HTML and JavaScript before attempting this tutorial.

WEB AND APPLICATION DEVELOPMENT ENGINEER

Introduction to Ingeniux Forms Builder. 90 minute Course CMSFB-V6 P

Building Java Servlets with Oracle JDeveloper

MarkLogic Server. Node.js Application Developer s Guide. MarkLogic 8 February, Copyright 2016 MarkLogic Corporation. All rights reserved.

Develop highly interactive web charts with SAS

FileMaker Server 9. Custom Web Publishing with PHP

An introduction to creating Web 2.0 applications in Rational Application Developer Version 8.0

An Introduction to Developing ez Publish Extensions

S.A.T.E.P. : Synchronous-Asynchronous Tele-education Platform

Course Structure of Three Year Degree B.A Programme in Computer Application under Semester System of Dibrugarh University (General Programme)

Web Services for Management Perl Library VMware ESX Server 3.5, VMware ESX Server 3i version 3.5, and VMware VirtualCenter 2.5

Web Development CSE2WD Final Examination June (a) Which organisation is primarily responsible for HTML, CSS and DOM standards?

PHP Language Binding Guide For The Connection Cloud Web Services

Transcription:

Chapter 2: Interactive Web Applications 2.1 Interactivity and Multimedia in the WWW architecture 2.2 Client-Side Multimedia in the Web (Example HTML5) 2.3 Interactive Server-Side Scripting (Example PHP) 2.4 Data Storage in Web Applications (Example Database Access in PHP) 2.5 Integrated Server/Client-Side Scripting (Example jquery/ajax) 1

Database Management Systems: A Quick Reminder Database: Structured collection of data items Stored persistently Provides access to a common data pool for multiple users Database Management System (DBMS): Collection of programs for administration and usage of a database Various base models for DBMS:» Old: network model, hierarchical model» Dominant: relational model» Alternative: object-oriented model Relational databases: Good methodological support for design of data schema Standardized language interface SQL (Structured Query Language) Document-oriented databases: Based on document trees, APIs for queries ( NoSQL ) 2

Prerequisites and Basic Architecture Database server Database 1 Database 2 Table 1.1 Table 1.2 Table 2.1 Table 2.2 Administration software User programs Other Servers (e.g. Web Server) 3

MySQL Open source software system Frequently used also in commercial context www.mysql.com Software package providing: Database server (mysqld) Administration program (mysqladmin) Command line interface (mysql) Various utility programs Communication between programs on local host: socket interface Bidirectional data stream exchange between programs Similar to files 4

Before Creating Anything in the Database... Using a database requires careful information design. Which are the data to be stored? Are there existing data to connect to? What is the schema of the data to be stored? E.g. Entity-Relationship diagrams as a tool Transformation into relational database schema (table design) Once a database is filled with data and in use, it is difficult to modify! Database schema design has to be carried out with great care! Most important rule: Avoid redundant storage of information But keep performance in mind... 5

Creating Database Tables (1) Prerequisites: Database server running Socket connection between programs intact User accounts with adequate privileges known First step: Create database Container for many tables Requires special privileges Example SQL: create database music; Second step: Choose used database Sets the context for further interactions Example SQL: use music 6

Creating Database Tables (2) Third step: Create tables According to earlier design Each table should provide a unique identifier (primary key) SQL Example: create table mysongs (code VARCHAR(5) primary key, title VARCHAR(20), artist VARCHAR(20), album VARCHAR(20), runtime INT); Fourth step: Fill tables with data Simplest case: Individual SQL commands Better: Import from structured data file Frequent: Special programs for importing and creating data SQL Example: insert into mysongs values ('1','One','U2','The Complete U2',272); 7

SQL Monitor Output 8

Queries with SQL 9

Server-Side Databases, PHP and MySQL Libraries for database access: "Database extensions for server-side scripts Depend on type of database May require additional installations For PHP and MySQL: MySQL database extensions usually pre-installed Three different APIs for PHP» Original MySQL API (deprecated since PHP 5.5)» MySQL Improved Extension (mysqli) used here» PHP Data Objects (PDO) interface 10

Excursus (1): Object-Orientation in PHP mysqli allows object-oriented programming Object-orientation: everything is an object objects encapsulate data --> logical grouping of variables and functions objects have attributes and methods in PHP (file lecture.php): class Lecture{ var $title = "Online Multimedia"; var $semester = "Winter 2015/2016"; var $professor = "Prof. Dr. Heinrich Hussmann"; var $guestlecturers = array(); function addlecturer($name){ $this->guestlecturers[] = $name; } } 11

Excursus (2): Using Classes in PHP To use the class in another script, it needs to be imported: require("lecture.php"); require_once("lecture.php"); Afterwards, classes can be instantiated and become objects that we can assign to variables: $mmn = new Lecture(); Accessing member variables and methods is done using the arrow notation: echo 'Semester'. $mmn->semester; $mmn->addlecturer("seitz"); foreach($mmn->guestlecturers as $lecturer){ echo $lecturer; } 12

Connecting to a Database from PHP Steps: Original SQL: First connect to server, then select (use) a database Improved PHP API: Combined into one step Connect to server and select a database Establish a connection for data exchange between Web Server/PHP plugin and database server Local communication (through socket), if both programs on same machine TCP/IP connection to remote server is possible Requires hostname, (MySQL) username, password, database name PHP: Create a new mysqli object» Returns an object which can be used for further operations Performance optimization: Persistent connections and connection pools 13

Example: Connecting to Database <?php $db = new mysqli('localhost','root','demopw','music'); if ($db->connect_error) { die('failed to connect: '.$db->connect_error); } echo 'Connected to server and DB selected.<br/>';...?> 14

Sending Database Queries from PHP Basic idea (in all programming language/database integrations): SQL queries given as strings to library functions MySQL/PHP: query()method of mysqli object Requires SQL query as parameter (optionally link to server as 2nd param.) "Query" includes also INSERT, UPDATE, DELETE, DROP (SQL)! Return value in case of SELECT, SHOW, DESCRIBE and similar: Result set represented as mysqli_result object Special functions and variables to process result data (examples): $num_rows (property)» Number of rows in the result set fetch_assoc()» Reads one row of result data and returns it as associative array» Makes the next row available 15

Example: Reading Data From a Query in PHP <?php $db = connecting, selecting $query = 'SELECT * FROM mysongs'; $result = $db->query($query); if (!$result) { die('query failed: '.$db->error); } while ($row = $result->fetch_assoc()){ foreach ($row as $element) { echo $element; echo ', '; } echo("<br/>"); }...?> dbaccess.php 16

Creating HTML Output From SQL Query (1) <!DOCTYPE html> <html> <head> <title>database table in HTML</title> </head> <?php $db = new mysqli('localhost','root','demopw','music'); if ($db->connect_error) { die('failed to connect: '.$db->connect_error); }?> dbaccess_html.php 17

Creating HTML Output From SQL Query (2)... <body> <h1>the following table is retrieved from MySQL:</h1> <table> <?php $query = 'SELECT * FROM mysongs'; $result = $db->query($query) or die ('Query failed'.$db->error); while ($row = $result->fetch_assoc()) { echo "\t<tr>\n"; foreach ($row as $element) { echo "\t\t<td>"; echo $element; echo "</td>\n"; } echo "\t</tr>\n"; }?> </table> 18

Creating HTML Output From SQL Query (3)... <?php $result->free(); $db->close();?> </body> </html> 19

Outlook: Using MongoDB (Document-Oriented) Heinrichs-MacBook-Pro: hussmann$ mongo MongoDB shell version: 2.6.5 > use music switched to db music > db.mysongs.insert({code:'1', title:'one', artist:'u2',album:'the Complete U2',runtime:272}) WriteResult({ "ninserted" : 1 }) > db.mysongs.find({runtime: {$gt: 250}}, {title: true}) { "_id" : ObjectId("5448042878b2c1f62e542dc4"), "title" : "One" } { "_id" : ObjectId("544804cf78b2c1f62e542dc5"), "title" : "Wheel in the Sky" } { "_id" : ObjectId("5448054978b2c1f62e542dc6"), "title" : "Lady in Black" } { "_id" : ObjectId("5448054e78b2c1f62e542dc7"), "title" : "Smoke on the Water" } >quit() JavaScript takes the role of SQL! 20

Chapter 2: Interactive Web Applications 2.1 Interactivity and Multimedia in the WWW architecture 2.2 Client-Side Multimedia in the Web (Example HTML5) 2.3 Interactive Server-Side Scripting (Example PHP) 2.4 Data Storage in Web Applications (Example Database Access in PHP) 2.5 Integrated Server/Client-Side Scripting (Example jquery/ajax) Literature: D.S. McFarland: JavaScript and jquery: The Missing Manual, 3rd ed., O Reilly 2014 http://jquery.com 21

jquery See jquery.com John Resig 2006 JavaScript Library to assist with traversal and manipulation of HTML through DOM event handling animations Simple AJAX applications (see later) Current versions: 1.11.3 and 2.1.4 Examples use 2.1.1 jquery is currently the most used JavaScript library 04 Nov 2015: 66.8% of all Websites, 95.6% market share in JS libraries (see http://w3techs.com/technologies/overview/javascript_library/all) Further libraries build on jquery (e.g. jqueryui) jquery is essentially one large JavaScript file included locally or through a delivery network of servers 22

Using jquery Include the library into any file where jquery is to be used Locally: <script type="text/javascript">jquery.js</script> From jquery Web site or through various Content Delivery Networks jquery is accessible as a global function and as an object instance Function jquery, abbreviated as $ jquery includes Sizzle engine to traverse and manipulate DOM trees Frequent pattern: $(selector-expression) jquery provides additional utility functions Frequent pattern: $.fname(parameters) jquery supports event handlers Frequent pattern: DOMObject.eventname(function) Convenient pattern: Using local anonymous functions jquery should be executed after DOM tree is ready (not necessarily after loading all content) Event handler for ready event 23

Event Handler for jquery ready Event Standard places to put jquery code: in a script block at the end of page executed when DOM tree has been loaded (event handler) <script src="jquery.js"></script> <script> function runjquery() { alert("run some jquery code now"); }; $( document ).ready(runjquery); </script> jq_init0.html 24

Using Anonymous Functions in JavaScript <script> function runjquery() { alert("run some jquery code now"); }; $( document ).ready(runjquery); </script> Rewritten with anonymous event handler: <script> $( document ).ready( function() { alert("run some jquery code now"); }; ); </script> jq_init1.html 25

Example: Interactive Highlighting in Table Assuming HTML and CSS code for table: <table> <thead> <tr> <th>#</th> <th>title</th>... </tr> </thead> <tbody> <tr> </tr> </tbody> </table> <td>1</td> <td>one</td>... <style> table {...} th, td {...} thead { background-color: black; color: white; } tr.hilite { background-color: grey; color: white; } </style> 26

jquery DOM Selection Typical selector arguments for $( selector ) document HTML element names Identifiers (referring to HTML id attribute): #ident CSS classes: :.classname Special filters: :filtername Path constraints: Space-separated list of selectors Have to appear as (possibly indirect) successors in tree Example: Handler hover event on table rows: $( 'tr' ).hover(function() {...hilite... }); hover: Same handler called on mouseenter and mouseleave event Does this select the appropriate parts of the page? jq_table1.html 27

jquery DOM Manipulation jquery provides functions to modify attributes of HTML elements modify CSS classes attached to HTML elements add or remove parts of the DOM tree retrieve HTML text from DOM tree create DOM tree from HTML strings Good practice: Use CSS, assign styles dynamically with jquery Add or remove class: object.addclass(class), object.removeclass(class) Toggle (add/remove) class: object.toggleclass(class) Example: $("#mysongs tbody tr").hover(function() { $( this ).toggleclass( "hilite" ); }); jq_table2.html 28

Example: Extending HTML Table Using jquery Make rows of the table selectable by adding a checkbox column jquery code for table head: $('#mysongs thead tr'). append(' <th>select</th>'); jquery code for table body: $('#mysongs tbody tr'). append(' <td style="text-align: center"> <input/ type="checkbox"> </td>'); jq_table3.html 29

Restructuring jquery Code Good practice: Re-use selection results (optimization) Apply concepts from functional programming: E.g. collection.each(fn): applies function fn to all objects contained in collection Example: $('#mysongs tbody tr').each(function(){ $(this).append(' <td style="text-align: center"> <input/ type="checkbox"> </td>'); $(this).hover(function(){ $(this).toggleclass('hilite'); }); 30

Method Chaining jquery: Most functions return an object compatible to the object on which the function was called Create method chains by function composition Simple generic example: $( ).addclass('classname'). css(css_prop, css_value); Executing another jquery query on result set: collection.find(' selector '); Running example: $(this).append(' <td style="text-align: center"> <input/ type="checkbox"></td>').find(':checkbox').change(event handler for change event); 31

Example: Highlighting Selected Rows in Table.find(':checkbox').change(function(){ if ($(this).prop('checked')) { $(this).parents('tr').addclass('checked'); numcheckedrows++; } else { (this).parents('tr').removeclass('checked'); numcheckedrows--; } parents(element_type): moves upwards in the tree and selects all elements of given element_type jq_table4.html 32

Animations in jquery jquery enables time-dependent transitions between CSS property values adjustable in duration and linearity ( easing in/out) Generic animation method: animate() Shortcut methods for frequent animations: show(speed), hide(speed) for DOM elements simple parameter speed with values slow, normal, fast Example: if (numcheckedrows==0) $('#btn').show("slow"); if (numcheckedrows==1) $('#btn').hide("slow"); More animations: https://api.jquery.com/category/effects/ jq_table5.html 33

Combining PHP, Database Access, jquery jquery code as part of server page in PHP/MySQL setting jquery/javascript sent from (PHP-enabled) Web server <body> <h1>the following table is retrieved from MySQL:</h1> <div style="width: 600px"> <table id="mysongs" style="width: 600px"> <thead>...</thead> <tbody> <?php $query = 'SELECT * FROM mysongs'; $result = mysql_query($query)...;...?> </tbody> </table> <input id='btn' type='button' value='...'></input> </div> </body> <script src="jquery.js"></script> <script> $( document ).ready(function() {...} </script> 34

Selecting Information Using jquery/dom Example: Get the IDs of all checked table rows For instance to put them into a shopping cart $('#btn').click(function(){ var selidstextarray = $('#mysongs input:checked'). map(function(){ return $(this).parents('tr').children().first().text() }). }) toarray(); map functional (also from functional programming): Applying a function pointwise to a collection dbaccess_jquery.php 35

Sending Selected Data to Server HTTP traditional synchronous way: Filling a form, sending a request (GET or POST) Request data: key-value pairs with simple value types Response data: HTML Waiting for response before updating page Modern asynchronous way ("AJAX"): Sending a request from JavaScript Request and response data: String encoding of data structures (e.g. JSON) Continue script in parallel to waiting for response AJAX is easy with jquery! 36

Sending Request Using jquery $('#btn').click(function(){ var selidstextarray = $('#mysongs input:checked'). map( ).toarray(); var selidsjson = JSON.stringify(selIdsTextArray); }); $.ajax({ type: 'POST', url: 'serverdummy.php', data: {selection: selidsjson} }); dbajax_jquery.php 37

serverdummy.php <?php $value = $_REQUEST['selection']; $file = fopen("dummydata.txt", "w"); if ($file) { fputs($file, "selection: ". $value. "\n"); fclose($file); }?> Of course, in a realistic setting, data received by the server is processed by operating background systems Here, may want to create a table in MySQL referring to mysongs table 38

Asynchronous Requests Returning a Result User Browser Open URL (php) HTML+JS/jQuery Server read DB AJAX request (jquery) read return data (e.g. JSON) 39

jquery AJAX Requests with Result jquery ajax method (and shorthands get and post) creates a request to server Standard arguments, like: url: URL address to send request to settings: Key-value pairs (may contain JSON data) Example settings: datatype: Kind of data expected for answer (e.g. xml, json, html) success(data,status): JavaScript function to be called in case of successful server response error (requestobj, message, errorobject): JavaScript function to be called in case of server response indicating errors contenttype: Kind of data sent to the server often 'application/json' 40