CMPE 280 Web UI Design and Development February 22 Class Meeting

Slides:



Advertisements
Similar presentations
WEB DESIGN TABLES, PAGE LAYOUT AND FORMS. Page Layout Page Layout is an important part of web design Why do you think your page layout is important?
Advertisements

CS 174: Web Programming January 27 Class Meeting
CS 174: Web Programming February 26 Class Meeting Department of Computer Science San Jose State University Spring 2015 Instructor: Ron Mak
Web Development & Design Foundations with XHTML Chapter 9 Key Concepts.
Building the User Interface by Using HTML5: Organization, Input, and Validation Lesson 3.
Internet Applications Spring Review Last week –MySQL –Questions?
CSCI 6962: Server-side Design and Programming Introduction to AJAX.
JavaScript, Fourth Edition Chapter 12 Updating Web Pages with AJAX.
CSC 2720 Building Web Applications HTML Forms. Introduction  HTML forms are used to collect user input.  The collected input is typically sent to a.
Tutorial 7 Creating Forms. Objectives Session 7.1 – Create an HTML form – Insert fields for text – Add labels for form elements – Create radio buttons.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
CS 174: Web Programming September 30 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
CS 174: Web Programming September 28 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
CS 174: Web Programming October 12 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Creating Dynamic Webpages
CS 174: Web Programming October 14 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
CHAPTER 7 JQUERY WHAT IS JQUERY? jQuery is a script. It is written in JavaScript.
CS 160 and CMPE/SE 131 Software Engineering February 11 Class Meeting Department of Computer Science Department of Computer Engineering San José State.
XHTML Forms.
CMPE 280 Web UI Design and Development September 7 Class Meeting
Introduction to.
CGS 3066: Web Programming and Design Spring 2017
CMPE 280 Web UI Design and Development August 29 Class Meeting
JavaScript.
JavaScript, Sixth Edition
Build in Objects In JavaScript, almost "everything" is an object.
CMPE 280 Web UI Design and Development September 14 Class Meeting
Applied Component I Unit II Introduction of java-script
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
CS 330 Class 7 Comments on Exam Programming plan for today:
How to Write Web Forms By Mimi Opkins.
CMPE 280 Web UI Design and Development September 26 Class Meeting
Data Virtualization Tutorial… CORS and CIS
CS1220 Web Programming Saloni Chacha.
In this session, you will learn about:
CMPE 280 Web UI Design and Development September 21 Class Meeting
CMPE 280 Web UI Design and Development October 19 Class Meeting
AJAX – Asynchronous JavaScript and XML
CMPE 280 Web UI Design and Development October 24 Class Meeting
CMPE 280 Web UI Design and Development October 26 Class Meeting
Intro to PHP & Variables
CMPE 280 Web UI Design and Development January 30 Class Meeting
Speaker Name Title of Presentation
Speaker Name Title of Presentation
Objectives Explore web forms Work with form servers
CS 174: Server-Side Web Programming February 14 Class Meeting
CMPE 280 Web UI Design and Development January 30 Class Meeting
The Internet 12/8/11 JavaScript Review
Introduction to Programming the WWW I
TITLE GOES HERE Your Subtitle
CMPE 280 Web UI Design and Development October 18 Class Meeting
CMPE 280 Web UI Design and Development January 29 Class Meeting
Creating Forms on a Web Page
CMPE 280 Web UI Design and Development March 19 Class Meeting
RESTful Web Services.
Tutorial 10: Programming with javascript
C++ Final Presentation.
PHP and JSON Topics Review JSON.
<form> Handling
Web Programming and Design
Web Programming and Design
HTML Introduction.
HTML Elements.
Business Flat General Ppt Template LOGO
CMPE 280 Web UI Design and Development August 27 Class Meeting
Unit 5 Create Forms.
AJAX By Prof. B.A.Khivsara
CMPE 280 Web UI Design and Development February 21 Class Meeting
CMPE 280 Web UI Design and Development March 19 Class Meeting
CMPE 280 Web UI Design and Development September 10 Class Meeting
Presentation transcript:

CMPE 280 Web UI Design and Development February 22 Class Meeting Department of Computer Engineering San Jose State University Spring 2018 Instructor: Ron Mak www.cs.sjsu.edu/~mak

Assignment #2 Requirements Assigned Thursday, Feb. 15 Due Monday, Feb. 26 At least one HTML form with input validation JavaScript and/or CSS Layout and formatting with CSS header and sidebar main body User interactivity with JavaScript It all happens in the browser only.

Assignment #2, cont’d This assignment is primarily about the client side. Make any necessary changes to your server-side code to make your client-side components work. Brief (2- or 3-page) report: Describes what input validation and interactivity features you added on the client side. Mention any improvements you may have made on the server side. Include any necessary instructions to run your code. port numbers, login usernames and passwords, etc.

More JavaScript Regular Expressions JavaScript uses regular expressions for more than just pattern matching. You can use regular expressions also for string manipulation.

Example: Reversing Names Suppose you had a list of names, such as You want to reverse the names, last name first, and insert a comma: Bill Clinton George Bush Barack Obama Donald Trump Clinton, Bill Bush, George Obama, Barack Trump, Donald Demo

Reversing Names, cont’d re/reverse.html <body> <h1>Reverse names:</h1> <form action=""> Enter a list of names with first name first, one per line:<br> <textarea id="names" rows="10" cols="50"></textarea> <p> <input type="button" value="Reverse names" onclick=reverseNames() /> <input type="reset" /> </p> </form> </body>

Reversing Names, cont’d function reverseNames() { var names = document.getElementById("names").value; var splitter = /\s*\n\s*/; var nameList = names.split(splitter); var newList = new Array; var reverser = /(\S+)\s(\S+)/; for (var i = 0; i < nameList.length; i++) { if (nameList[i].trim().length > 0) { newList[i] = nameList[i].replace(reverser, "$2, $1"); newNames += newList[i] + "\n"; } document.getElementById("names").value = newNames; re/reverse.js Use the pattern to split the string into an array of names. The pattern separates the names. \s is a whitespace character. We can improve this regular expression! \S = non-whitespace character Replace each name string according to the matching pattern.

Example: Formatting Names Suppose you allow users to be sloppy: But you still want: BiLL CLinTON GeOrGe BuSh barack OBAMA dOnAlD truMP Clinton, Bill Bush, George Obama, Barack Trump, Donald Demo

Formatting Names, cont’d Our regular expression for formatting names: Split the first and last names each into an initial letter followed by the rest of the letters. Call the regular expression’s exec() method on a string. Automatically sets JavaScript’s built-in RegExp object. Use RegExp.$1, RegExp.$2, etc. to access stored parts of the match. var formatter = /\s*(\S)(\S+)\s+(\S)(\S+)\s*/

Formatting Names, cont’d re/format.js var newNames = ""; for (var i = 0; i < nameList.length; i++) { if (nameList[i].trim().length > 0) { formatter.exec(nameList[i]); newList[i] = RegExp.$3.toUpperCase() + RegExp.$4.toLowerCase() + ", " + RegExp.$1.toUpperCase() + RegExp.$2.toLowerCase(); newNames += newList[i] + "\n"; }

More Document Object Model (DOM) Recall the DOM. Example: JavaScript, 9th ed. by Tom Negrino and Dori Smith Peachpit Press, 2015 ISBN 978-0-321-99670-1

DOM, cont’d Also recall how we used innerHTML and JavaScript to modify the DOM: <body> <form action=""> <fieldset> ... </fieldset> </form> <div id="outputDiv"> <p>Output will appear here.</p> </div> </body> document.getElementById("outputDiv").innerHTML = "<p><strong>" + x + " + " + y + " = " + sum + "</strong></p>”;

DOM, cont’d Using innerHTML is error-prone. document.getElementById("outputDiv").innerHTML = "<p><strong>" + x + " + " + y + " = " + sum + "</strong></p>"; Using innerHTML is error-prone. You can create elements with unclosed tags, or invalid tags. A safer way to modify the DOM is to use JavaScript’s DOM manipulation API. Demo

Example: DOM Modification <head>     <title>Node Actions</title>     <script src="nodes.js"></script> </head> <body>     <h1>Node actions</h1>     <form id="theForm">         Enter some text and choose an action:         <p><textarea id="textArea" rows="5" cols="30"></textarea></p>         <p>             Node action:             <select id="chooser">                 <option value="Add">Add to end</option>                 <option value="Insert">Insert before</option>                 <option value="Replace">Replace</option>                 <option value="Delete">Delete</option>             </select>             Paragraph:              <select id="indexer"></select>             <input type=button value="Do it!" onclick=nodeAction() />         </p>     </form>     <hr />     <div id="workspace"> </div> </body> dom/nodes.html The node whose children we will manipulate using JavaScript’s DOM API.

DOM Modification, cont’d dom/nodes.js window.onload = init; var textArea; var chooser; var indexer; var workspace; function init() { textArea = document.getElementById("textArea"); chooser = document.getElementById("chooser"); indexer = document.getElementById("indexer"); workspace = document.getElementById("workspace"); }

DOM Modification: Add a Child Node dom/nodes.js function addNode() { var text = textArea.value; var textNode = document.createTextNode(text); var pNode = document.createElement("p"); pNode.appendChild(textNode); workspace.appendChild(pNode); textArea.value = ""; }

DOM Modification: Insert a Child Node dom/nodes.js function insertNode() { var textNode = textArea.value; var index = indexer.selectedIndex; var textNode = document.createTextNode(textNode); var pNode = document.createElement("p"); pNode.appendChild(textNode); var pNodes = workspace.getElementsByTagName("p"); var chosenPNode = pNodes.item(index); workspace.insertBefore(pNode, chosenPNode); textArea.value = ""; }

DOM Modification: Replace a Child Node dom/nodes.js function replaceNode() { var text = textArea.value; var index = indexer.selectedIndex; var textNode = document.createTextNode(text); var pNode = document.createElement("p"); pNode.appendChild(textNode); var pNodes = workspace.getElementsByTagName("p"); var chosenPNode = pNodes.item(index); workspace.replaceChild(pNode, chosenPNode); textArea.value = ""; }

DOM Modification: Delete a Child Node dom/nodes.js function deleteNode() { var index = indexer.selectedIndex; var pNodes = workspace.getElementsByTagName("p"); var chosenPNode = pNodes.item(index); workspace.removeChild(chosenPNode); }

Custom JavaScript Objects At run time, a JavaScript variable can have any value. Create a custom object simply by giving it properties and methods.

Example Custom JavaScript Object objects/person.html var person = new Object(); person.name = "Mary"; person.age = 20; person.nextYear = function() { return this.age + 1; }; alert("Name = " + this.name + ", age = " + this.age + ", age next year = " + this.nextYear()); Demo

JavaScript Classes and Objects A JavaScript class has a constructor function. Example: Convention: Capitalized constructor name. function Person(name, age) { this.name = name; this.age = age; this.nextYear = function() return this.age + 1; }; }

Example Object Instantiation Use the constructor to create new instances: objects/people.html function createPeople() { mary = new Person("Mary", 20); john = new Person("John", 25); showPerson(mary); showPerson(john); } function showPerson(p) alert("Name = " + p.name + ", age = " + p.age + ", age next year = " + p.nextYear()); Demo

Prototype Objects A JavaScript class is a set of objects that inherit properties from the same prototype object. Person.prototype = { toString: function() { return "Person[name: '" + this.name + "', age: " + this.age + "]"; } function createPeople() mary = new Person("Mary", 20); john = new Person("John", 25); alert(mary); alert(john); objects/prototype.html Demo

Web Browser – Web Server Cycle Each time you submit form data from the web browser to the web server, you must wait for: The data to upload to the web server. The web server to generate the next web page. The next web page to download to your browser. Your browser to render the next web page. You experience a noticeable page refresh.

Web Browser – Web Server Cycle, cont’d Example: Click the submit button. JavaScript code on the server opens and reads a text file and generates a new web page containing the contents of the text file. The browser displays the new web page.

Web Browser – Web Server Cycle, cont’d <body>     <form action="text-response"           method="get">         <fieldset>             <legend>User input</legend>             <p>                 <label>First name:</label>                 <input name="firstName" type="text" />             </p>                 <label>Last name:</label>                 <input name="lastName" type="text" />                              <input type="submit" value="Submit" />         </fieldset>     </form> </body> Client side

Web Browser – Web Server Cycle, cont’d Server side // Process the form data and send a response. app.get('/text-response’,      function(req, res)     {         var firstName = req.param('firstName');         var lastName  = req.param('lastName');         var html = 'Hello, ' + firstName + ' ' + lastName + '!';                  res.send(html);     } );

AJAX Asynchronous JavaScript and XML Tighter communication between the web browser and the web server. Shortens the browser-server cycle. The server generates and downloads part of a page. The web browser refreshes only the part of the page that needs to change. The browser and server work asynchronously. The browser does not have to wait for the download from the server.

AJAX Example We will compare AJAX to non-AJAX. Demo

AJAX Example, cont’d var express = require('express'); routes/index.js var express = require('express'); var router = express.Router(); var ctrlMain = require("../controllers/main"); router.get('/', ctrlMain.home); router.get('/non-ajax', ctrlMain.get_nonajax); router.post('/non-ajax', ctrlMain.post_nonajax); router.get('/ajax', ctrlMain.get_ajax); router.post('/ajax', ctrlMain.post_ajax); module.exports = router;

AJAX Example, cont’d var lineReader = require('line-reader'); function sendPage(fileName, result) {     var html = '';          lineReader.eachLine(fileName,         function(line, last)         {             html += line + '\n';             if (last)              {                  result.send(html);                 return false;              }             else             {                 return true;         }); } controllers/main.js

AJAX Example, cont’d controllers/main.js module.exports.home = function(request, result)  {     sendPage('index.html', result); }; module.exports.get_nonajax = function(request, result)      sendPage('nonajax.html', result); module.exports.post_nonajax = function(request, result)      sendPage('nonajax2.html', result); module.exports.get_ajax = function(request, result)      sendPage('ajax.html', result); module.exports.post_ajax = function(request, result)      sendPage('lorem.txt', result); controllers/main.js

AJAX Example, cont’d nonajax.html <head> ...     ...     <script type="text/javascript" src="common.js"></script> </head> <body onload = "init()">     <h1>Non-AJAX</h1>          <canvas id = "canvas"             height = "200"             width = "200">         <p>Canvas not supported!</p>     </canvas>     <form action="non-ajax" method="post">         <input type="submit" />     </form>     <hr />     <div id="output">         <p>             Watch this space!         </p>     </div> </body> nonajax.html

AJAX Example, cont’d <head> ...     ...     <script type="text/javascript" src="common.js"></script> </head> <body onload = "init()">     <h1>Non-AJAX</h1>          <div id="output">         <p>             Lorem ipsum dolor sit amet, <br>             consectetur adipiscing elit, <br>             sed do eiusmod tempor incididunt <br>             ut labore et dolore magna aliqua.                 </p>     </div> </body> nonajax2.html

AJAX Example, cont’d const CANVAS_W = 200; const CANVAS_H = 200; const IMAGE_W  = 20; const IMAGE_H  = 20; const RIGHT    = CANVAS_W - IMAGE_W; const BOTTOM   = CANVAS_H - IMAGE_H; var con; var image; var x  = 0; var y  = 0; var dx = 5; var dy = 3; function init() {     con = document.getElementById("canvas")           .getContext("2d");     con.strokeStyle = "black";               setInterval(draw, 50); } public/common.js

AJAX Example, cont’d public/common.js function draw() {     con.fillStyle = "white";     con.fillRect(0, 0, CANVAS_W, CANVAS_H);     con.strokeRect(0, 0, CANVAS_W, CANVAS_H);          con.fillStyle = "green";     con.fillRect(x, y, IMAGE_W, IMAGE_H);     x += dx;     y += dy;     // Bounce off a wall     if ((x < 0) || (x > RIGHT))  dx = -dx;     if ((y < 0) || (y > BOTTOM)) dy = -dy; }

AJAX Example, cont’d ajax.html <head> ...     ...     <script type = "text/javascript" src="common.js"></script> </head> <body onload = "init()">     <h1>AJAX</h1>          <canvas id = "canvas"             ...     </canvas>     <form action="">         <button type="button"                  onclick="doAJAX()">             Click for AJAX!         </button>     </form>     <hr />     <div id="output">         <p>Watch this space!</p>     </div> </body> ajax.html

AJAX Example, cont’d public/common.js var request; function doAJAX() {     request = new XMLHttpRequest();     request.open("POST", "/ajax");     request.onreadystatechange = displayFile;     request.send(null); } function displayFile()     if (request.readyState == 4) {         if (request.status == 200) {             var text = request.responseText;             text = text.replace(/\n/g, "<br />");             document.getElementById("output").innerHTML =                     "<p>" + text + "</p>";         }     } Function displayFile() will be called asynchronously.

The XMLHttpRequest Object Use the properties and methods of the XMLHttpRequest object to control a request from the web browser to the web server. See also: http://www.w3schools.com/xml/dom_http.asp JavaScript, 9th ed. by Tom Negrino and Dori Smith Peachpit Press, 2015 ISBN 978-0-321-99670-1

readyState Property Values JavaScript, 9th ed. by Tom Negrino and Dori Smith Peachpit Press, 2015 ISBN 978-0-321-99670-1