Lecture #6 Dynamic Web Documents HAIT Summer 2005 Shimrit Tzur-David 1 Client-Server Architecture • In a client-server architecture, computation is done either in the client or in the server • There are cases where we can choose whether to perform the computation in the client or in the server • There are cases where we cannot choose where to perform the computation – For example, accessing a database 2 Form Validation • Consider the case where a user is required submit his name to a server application • Where, for example, should we check that the inserted value is not an empty string? – In the client (i.e., the Web browser)? – In the server? 3 Client Side Technologies • Javascript – Developed by Netscape – Supported by all browsers (although not all support the standard) – Very light (no graphics) and good interaction with HTML • Java Applets – Developed by Sun – In the past it was supported by all browsers, but not any more – Capable of doing almost anything that Java allows 4 JavaScript Overview • A "scripting" language for HTML pages • The code is embed in HTML pages • The browser interprets and executes the script (it is not compiled) • Do not declare data types for variables (loose typing) • Dynamic binding – object references checked at runtime 5 Overview – Cont. • Scripts can manipulate "browser objects:" – – – – HTML form elements Images Frames etc. • For security – cannot write to disk (when run on a client) 6 Abilities • • • • Generating HTML content dynamically Monitoring and responding to user events Validate forms before submission Interact with the frames and windows of the browser • Customize pages to suit users 7 Example Why do we need <br> if we used writeln? <HTML> <HEAD><TITLE>An Hello World Example</TITLE> <SCRIPT LANGUAGE = "JavaScript"> document.write("<font size='+4'>"); document.writeln("Hello World!<br>"); document.writeln("What a boring example</font>") </SCRIPT> </HEAD> <BODY> <!-- An empty document body --> </BODY> </HTML> 8 Example – Cont. 9 Example 2 <HTML> <HEAD><TITLE>An Hello World Example</TITLE> <SCRIPT LANGUAGE = "JavaScript"> document.write("<font size='+4'>"); document.writeln("Hello World!<br>"); document.writeln("What a boring example</font>") </SCRIPT> </HEAD> <BODY> <h1>My Hello World Example</h1> </BODY> </HTML> 10 Example 2 – Cont. 11 Example 3 <HTML> <HEAD><TITLE>An Hello World Example</TITLE> <SCRIPT LANGUAGE = "JavaScript"> document.write("<font size='+4'>"); document.writeln("Hello World!<br></font>"); </SCRIPT> </HEAD> <BODY> <h1>My Hello World Example</h1> <SCRIPT LANGUAGE = "JavaScript"> document.writeln("What a boring example") </SCRIPT> </BODY> </HTML> 12 Example 3 – Cont. 13 JavaScript Variables • Untyped! • Can be declared with var keyword: var foo; • Can be created automatically by assigning a value: val has changed from an int to a String! val = 1; val = “Thank for all the fish"; 14 Variables Names • A variable name can be any valid identifier • The identifier is a series of characters – Consisting of letters (lower and upper case), digits, and underscores (_) – Does not begin with a digit – Does not contain any space • Javascript is case sensitive (foo and FOO are different) 15 Variables • Local variable is available only in the function where it is declared • Global variable is available all over the document • A variable declaration – Inside a function creates a local variable – Outside a function creates a global variable • Local variables must be declared with var 16 Literals • The typical bunch: – Numbers 17 123.45 – Strings “Let it be” – Boolean: true false – Arrays:[1,“ab ba”,17.234] – null – undefined Arrays can hold anything! 17 Operators • Arithmetic, comparison, assignment, bit wise, Boolean (pretty much just like Java) + - * / % ++ -== != > < >= <= && || ! & | << >> += -= *= /= %= 18 The Special Plus Command • Which of the following two is correct? • What is the ‘type’ of the answer? String x = “The answer is” + 42 y = 42 + “is the answer” 19 Which is correct? • Which of the following two is correct? • What is the ‘type’ of the answer? String, output: 377 Number, output: 30 x = "37" + 7 y = "37" - 7 20 Types of Equality • The equals == checks if both operands are equal after performing type conversion • The equals === checks if both operands are of the same type and equal true • Example: – Is 3 == "3" (true or false?) – Is 3 === "3" (true or false?) false 21 Conditional Operators • equals if (a == b) {…} • not equals if (a != b) {…} • greater than or equal to if (a >= b) {...} • less than or equal to if (a <= b) {...} 22 Boolean Operators • and if (true && true) {…} • or if (true || false) {…} • not if (! false) {...} 23 <HTML> <HEAD><TITLE>Using Variables</TITLE> <SCRIPT LANGUAGE = "JavaScript"> var firstNumber = 11, secondNumber = 23, sum; sum = firstNumber + secondNumber; document.write("<FONT COLOR = 'blue' SIZE = '6'>The sum of " + firstNumber + " and " + secondNumber + " is </FONT>"); document.write(" <FONT COLOR = ‘red' SIZE = '7'>" + sum + "</FONT>"); </SCRIPT> </HEAD> <BODY> <!-- An empty document body --> </BODY> </HTML> 24 25 JavaScript Constructs • condition (selection) if (condition) {statements if true} else {statements if false} if (metushelahAge < yourAverageAge) { document.write ("<body><h2>its true that Metushelah is younger than most of you,") document.write ("<br>computers never lie!</h2> </body>") } 26 JavaScript Constructs • loop (iteration): both for and while loops are available for (var i=0; i < myform.myAge.value.length; i++) { var oneChar=myform.myAge.value.substring (i, i+1) if (oneChar < "0" || oneChar > "9") { alert("Please enter a valid number " + oneChar + " is not valid.") } } 27 <HTML> <HEAD><TITLE>Loops Example</TITLE> <SCRIPT LANGUAGE = "JavaScript"> for (var counter = 1 ; counter <= 8 ; ++counter) { document.write(“<P><FONT COLOR = ‘blue’ SIZE = ‘ “ + counter + “ '> Now with font size " + counter + " </FONT></P> “); } </SCRIPT> </HEAD> <BODY> <!-- An empty document body --> </BODY> </HTML> 28 29 JavaScript Functions • Functions are first class citizens • The keyword function used to define a function (subroutine): function add(x,y) { return(x+y); } 30 Function Input and Output • Numbers and Boolean values always passed to functions using call-by-value • For objects, a call-by-reference is used to pass them to the functions • Numbers and Boolean values are always returned by value • Objects returned by reference 31 Example • The next example uses functions to computing the Fibonacci numbers • Note the use of recursion • Be careful, some browsers may not deal well with very big numbers in the input (i.e., too many recursive calls) 32 <HTML> <HEAD><TITLE>Functions Example</TITLE> <SCRIPT LANGUAGE = "JavaScript"> function fibonacciValue() { var value = parseInt(document.fibonacciForm.number.value ); window.status = "Calculating Fibonacci number for " + value; document.fibonacciForm.result.value = fibonacci(value); window.status = "Done Calculating Fibonacci number"; } function fibonacci( n ) { if (n == 0 || n == 1) return n; else return fibonacci( n - 1 ) + fibonacci( n - 2 ); } </SCRIPT></HEAD> 33 <BODY> <FORM NAME = "fibonacciForm"> <TABLE BORDER = "1" BGCOLOR = “fabbfc"> <TR><TD BGCOLOR = “eabbfc">Enter a number</TD> <TD><INPUT NAME = "number" TYPE = "text"></TD> <TD><INPUT TYPE = "button" VALUE = "Calculate" ONCLICK = "fibonacciValue()"</TR> <TR><TD BGCOLOR = “fabbfc">Fibonacci Value</TD> <TD><INPUT NAME = "result" TYPE = "text"> </TD> </TR> </TABLE> </FORM> </BODY> </HTML> 34 Function Arguments • Within a function, its arguments can be accessed with arguments[i]. • The number of arguments is arguments.length • A function can be created that takes any number of arguments 35 Example function myConcat(separator) { result="" // initialize //What does this return? list // iterate through arguments for (var i=1; i<arguments.length; i++) { result += arguments[i] + separator } return result } red%orange%blue myConcat(“%","red","orange","blue") 36 Objects • Objects have attributes and methods • There are pre-defined objects and user-defined object types • Using objects has similarity to the syntax of C/Java: objectName.attributeName objectName.methodName() 37 Objects Are Like Arrays myCar.make = "Ford" myCar.model = "Mustang" myCar.year = 66; myCar[“make”] = "Ford" myCar[“model”] = "Mustang" myCar[“year”] = 66; 38 function show_props(obj, obj_name) { var result = "" for (var i in obj) result += obj_name + "." + i + " = " + obj[i] + "\n" return result } So, the function call show_props(myCar, "myCar") would return the following: myCar.make = Ford myCar.model = Mustang myCar.year = 66 39 Creating a New Object • There are two ways to create new objects: • Object Initializer: – objectName={prop1:val1, …, propN:valN} • Constructor Function: – define a constructor function – create the new object using new 40 Example function car(make, model, year) { this.make = make this.model = model this.year = year } theMazda = new car(“Mazda", “323", 1991) theHonda = {make:”Honda”, year:1992, color:"red",wheels:4, engine:{cylinders:4,size:2.2}} 41 Creating a Method • A method of an object is a function that has been assigned to the object: object.methodName = functionName 42 Example function displayCar() { var result = "A Beautiful " + this.year + " " + this.make + " " + this.model; document.writeln(result) } function car(make, model, year) { this.make = make this.model = model this.year = year this.displayCar = displayCar } 43