Client-Server Architecture
In a client-server architecture, computation is done
either in the client or in the server
Client Side Programming There are cases where we can choose whether to
perform the computation in the client or in the
server
Representation and Management For example, transforming an XML document using XSL
of Data on the Web There are cases where we cannot choose where
to perform the computation
For example, accessing a database
Strengths and Weaknesses of
Server-Side Computation Form Validation
Strengths Weaknesses Consider the case where a user is required
allows access to server puts most of processing
submit her name to a server application
files and databases load on server
makes no assumptions requires round-trip for Where, for example, should we check that
about client computer every submission, using
the inserted value is not an empty string?
capabilities, puts little valuable bandwidth
burden on it cannot provide In the client (i.e., the Web browser)?
easier to manage and instantaneous response In the server?
control on server expected with GUI
more secure for client less secure for server
Client Side Technologies About Applets
Javascript
Developed by Netscape An Applet is a Java application, embedded
Supported by all browsers (although not all support the standard)
in a Web page
Very light (no graphics) and good interaction with HTML
<APPLET CODE= AppletClass WIDTH=x HEIGHT=y/>
VBScript
Developed by Microsoft When a browser loads the Web page, the
Supported only by Microsoft Internet Explorer
A light version of Microsoft Visual Basic applet byte-code is downloaded to the client
Java Applets box and executed by the browser
Developed by Sun
In the past it was supported by all browsers, but not any more Commonly used for: games, graphics, etc.
Capable of doing almost anything that Java allows
Applets Limitations
Security Restrictions: Applets cannot access files
in the client computer nor files (or databases)
behind a firewall
The Bandwidth Problem: Applets are usually large
in comparison to HTML files, thus , the download
time becomes unacceptable
Compatibility:
Client must have a compatible browser
Thin clients may not support the whole Java API
Overview
A "scripting" language for HTML pages
The code is embed in HTML pages
Javascript 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
Overview (cont.) Abilities
Scripts can manipulate "browser objects:" Generating HTML content dynamically
HTML form elements Monitoring and responding to user events
Images Validate forms before submission
Frames Manipulate HTTP cookies
etc. Interact with the frames and windows of the
For security cannot write to disk (when run browser
on a client) Customize pages to suit users
It is not Java Web Architecture for JavaScript
"CLIENT" "SERVER"
Desktop access Remote host
Java : Web browser
Web
(HTTP)
compilation required (not a script) HTML Page: HTML/HTTP HTML/HTTP Server
<SCRIPT> Internet
TCP/IP TCP/IP
can create stand alone application </SCRIPT>
object-oriented
Why is it called Javascript then? built-in
JavaScript
interpreter HTML
pages w/
embedded
script
:K\GRZH
Example QHHGEU!LIZH
XVHGZULWHOQ"
<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>
Example
<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>
Some of Javascript Reserved
Example
<HTML>
Keywords
<HEAD><TITLE>An Hello World Example</TITLE> break function true
<SCRIPT LANGUAGE = "JavaScript">
document.write("<font size='+4'>");
case if typeof
document.writeln("Hello World!<br></font>"); continue in var
</SCRIPT>
delete new void
</HEAD>
<BODY> <h1>My Hello World Example</h1> do null while
<SCRIPT LANGUAGE = "JavaScript">
else return with
document.writeln("What a boring example")
</SCRIPT> false switch
</BODY> for
:KDWZLOOKDSSHQ"
this
</HTML>
Non Used Reserved Words Javascript Variables
catch extends Untyped!
class finally
Can be declared with var keyword:
const import var foo;
debugger super
Can be created automatically by assigning a
default try value: YDO KDVFKDQJHGIURPDQ
enum val = 1;
LQWWRD6WULQJ
export val = Thank for all the fish";
Variables Names Variables
A variable name can be any valid identifier Local variable is available only in the function
The identifier is a series of characters where it is declared
Consisting of letters (lower and upper case), digits, and Global variable is available all over the document
underscores (_)
A variable declaration
Does not begin with a digit
Does not contain any space Inside a function creates a local variable
Outside a function creates a global variable
Javascript is case sensitive (foo and FOO are Local variables must be declared with var
different)
Literals Operators
The typical bunch: Arithmetic, comparison, assignment, bit
Numbers 17 123.45 wise, Boolean (pretty much just like Java)
Strings L et it be
Boolean: true false + - * / % ++ --
Arrays: [1, ab ba ,17.234] == != > < >= <=
null && || ! & | << >>
You can use typeof(A)
undefined to get the type of A:
+= -= *= /= %=
number, string, object..
Arrays can hold anything!
The Special Plus Command Which is correct?
Which of the following two is correct? Which of the following two is correct?
What is the type of the answer? What is the type of the answer?
x = The answer is + 42 x = "37" + 7
y = 42 + is the answer y = "37" - 7
Types of Equality Types of Inequality
The equals == checks if both operands are The equals != checks if both operands are
equal after performing type conversion unequal after performing type conversion
The equals === checks if both operands are The equals !== checks if both operands are
of the same type and equal not of the same type and or not equal
Example: Example:
Is 3 == "3" (true or false?) Is 3 != "3" (true or false?)
Is 3 === "3" (true or false?) Is 3 !== "3" (true or false?)
Conditional Operators Boolean Operators
equals and
if (a == b) { }
if (true && true) { }
not equals
or
if (a != b) { }
if (true || false) { }
greater than or equal to
if (a >= b) {...} not
less than or equal to if (! false) {...}
if (a <= b) {...}
<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>
Control Structures JavaScript Constructs
Some just like Java: sequence (block)
if if-else ?: switch executes with no conditions
for while do-while semicolons optional using one statement per
line, but not a bad thing to use all the time
And a few not like in Java var metushelahAge = 130; var yourAverageAge
yourAverageAge = metushelahAge - 98
for (var in object)
var myObject = new Object("initial value")
with (object) more statements here..
«..
JavaScript Constructs JavaScript Constructs
condition (selection) loop (iteration): both for and while loops are
if (condition) {statements if true} available
else {statements if false}
for (var i=0; i < inputAge.length; i++) {
if (metushelahAge < yourAverageAge) { var oneChar = inputAge.substring (i, i+1)
document.write ("<body><h2>its true that if (oneChar < "0" || oneChar > "9") {
Metushelah is younger than most of you,") alert("Please enter a valid number ´
document.write ("<br>computers never lie!</h2> + oneChar + " is not valid.")
</body>") }
}
}
<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>
JavaScript Functions Function Input and Outout
Functions are first class citizens Numbers and Boolean values always
The keyword function used to define a passed to functions using call-by-value
function (subroutine): For objects, a call-by-reference is used to
pass them to the functions
function add(x,y) { Numbers and Boolean values are always
return(x+y); returned by value
} Objects returned by reference
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)
<HTML> <BODY>
<HEAD><TITLE>Functions Example</TITLE> <FORM NAME = "fibonacciForm">
<SCRIPT LANGUAGE = "JavaScript"> <TABLE BORDER = "1" BGCOLOR = ´fabbfc">
function fibonacciValue() { <TR><TD BGCOLOR = ´eabbfc">Enter a number</TD>
var value = parseInt(document.fibonacciForm.number.value ); <TD><INPUT NAME = "number" TYPE = "text"></TD>
window.status = "Calculating Fibonacci number for " + value; <TD><INPUT TYPE = "button" VALUE = "Calculate"
document.fibonacciForm.result.value = fibonacci(value); ONCLICK = "fibonacciValue()"</TR>
window.status = "Done Calculating Fibonacci number"; <TR><TD BGCOLOR = ´fabbfc">Fibonacci Value</TD>
} <TD><INPUT NAME = "result" TYPE = "text"> </TD>
function fibonacci( n ) { </TR>
if (n == 0 || n == 1) return n; </TABLE>
else return fibonacci( n - 1 ) + fibonacci( n - 2 ); </FORM>
} </BODY>
</SCRIPT></HEAD> </HTML>
Function Arguments Example
function myConcat(separator) {
Within a function, its arguments can be result="" // initialize list
accessed with arguments[i]. // iterate through arguments
for (var i=1; i<arguments.length; i++) {
The number of arguments is result += arguments[i] + separator
arguments.length }
return result
A function can be created that takes any }
number of arguments
//What does this return?
myConcat(", ","red","orange","blue")
Global Functions Objects
Javascript include several predefined functions that Objects have attributes and methods
you can use
There are pre-defined objects and user-
For example,
defined object types
eval(code-string) gets a string of JavaScript
code, evaluates it and executes it Using objects has similarity to the syntax of
It allows dynamic code execution C/Java:
parseInt(string) takes a string argument and
converts its beginning to an integer number (or return
objectName.attributeName
NaN) objectName.methodName()
Objects Are Like Arrays function show_props(obj, obj_name) {
var result = ""
for (var i in obj)
myCar.make = "Ford" result += obj_name + "." + i +
myCar.model = "Mustang" " = " + obj[i] + "\n"
myCar.year = 66; return result
}
So, the function call
show_props(myCar, "myCar")
would return the following:
myCar[ make ] = "Ford"
myCar[ model ] = "Mustang" myCar.make = Ford
myCar[ year ] = 66; myCar.model = Mustang
myCar.year = 66
Creating a New Object Example
function car(make, model, year) {
There are two ways to create new objects: this.make = make
this.model = model
Object Initializer: this.year = year
objectName={prop1:val1, , propN:valN} }
Constructor Function:
define a constructor function theMazda = new car( Mazda", 3 23", 1991)
theHonda = {make: Honda , year:1992,
create the new object using new color:"red",wheels:4,
engine:{cylinders:4,size:2.2}}
Creating a Method Example
A method of an object is a function that has function displayCar() {
var result = "A Beautiful " + this.year +
been assigned to the object: " " + this.make + " " + this.model;
document.writeln(result)
}
function car(make, model, year) {
object.methodName = functionName this.make = make
this.model = model
this.year = year
this.displayCar = displayCar
}
6HWWLQJWKHPHWKRG
Eval Example Deleting an Object
function stone(str) { To delete an object just set the object
eval("this."+str)
this.y=43 reference to null
this["z"] = 44
} When are objects that are not set to null
being removed?
flint = new stone("x=42")
document.write("<BR>flint.x is " + flint.x)
document.write("<BR>flint.y is " + flint.y)
document.write("<BR>flint.z is " + flint.z)
Array Objects Creating a New Array
Arrays are supported as objects var a = [ red , blue , g reen ]
Allocates an array of 3 cells and initializes the
Attribute length
values
Methods include: var b = new Array(5)
concat, join, pop, push, reverse, Allocates an array of 5 cells without initializing
sort values
var c = new Array()
Creates a new empty array
Array Example Code Understanding Arrays
Array literals:
arr1 = ["hello", 1, 33]
var a = [8,7,6,5];
Accessing arrays: (what is the result of)
document.writeln(arr1.length)
for (i=0;i<a.length;i++)
document.writeln(arr1[0])
a[i] += 2;
document.writeln(arr1["abc"])
b = a.reverse(); arr1[10]=66
document.writeln(arr1.length)
<HTML><HEAD><TITLE>Arrays Example</TITLE>
Passing Arrays to Functions <SCRIPT LANGUAGE = "JavaScript">
function start() {
var colors = ["red", "blue", "green"]
Arrays can be passed to functions as
printArray(colors);
arguments printArray(colors);
}
The array is passed by call-by-reference function printArray( arr) {
for (var i in arr) {
The name of the array is given to the
document.writeln("<FONT SIZE=5 COLOR=" + arr[i] + ">"
function + arr[i] + " </FONT><BR>");
arr[i] = "gray";
}
} </SCRIPT>
</HEAD><BODY ONLOAD = "start()"> </BODY></HTML>
Multidimentional Arrays
var matrix = [ [0, 1, 1], [1, 1, 0], [0, 0, 0]];
var myArray = [[1, 2, 3], [1], [1, 2]];
Going over the array
for (var i in myArray ) {
for (var j in myArray[i])
document.write(myArray[i][j]);
Other Object Types Math Common Methods
String: manipulation methods abs(x) cos(x)
Math: trig, log, random numbers round(x) sin(x)
ceil(x) tan(x)
Date: date conversions
floor(x) exp(x)
RegExp: regular expressions
max(x, y) pow(x, y)
Number: limits, conversion to string
min(x, y) sqrt(x)
0DWK$OVRLQFOXGHV log(x)
FRQVWDQWV
VXFKDV0DWK(0DWK3,
String Common Methods Date Common Methods
charAt (index) slice(start, end) getDate(), getFullYear(), getMonth(), getDay
charCodeAt(index) split(string)
getTime(), getHours(), getMinutes(),
concat(string) substr(start, length)
fromCharCode(value1,
getSeconds(), getMilliseconds()
substring(start, end)
value2, )
toLowerCase()
indexOf(substring, index)
toUpperCase()
lastIndexOf(substring,
index) toString()
valueOf()
<HTML>
<HEAD><TITLE>Time Example</TITLE> <BODY>
<SCRIPT LANGUAGE = "JavaScript"> <FORM NAME="timesForm">
function getTimes() { <P>
var current = new Date();
<INPUT NAME = "getTimeButton" TYPE = "button"
var out = "Day: " + current.getDay()+"\n";
VALUE = "Get Time" ONCLICK = "getTimes()">
out = out.concat("Month: " + current.getMonth() + "\n");
<P>
out = out.concat("Year: " + current.getFullYear() + "\n");
out = out.concat("GMT Time: " + current.toUTCString() + <TEXTAREA NAME = "output" ROWS ="10"
"\n"); COLS="42">
out = out.concat("Time: " + current.toString() + "\n"); </TEXTAREA>
document.timesForm.output.value = out; </FORM>
}
</BODY>
</SCRIPT>
</HTML>
</HEAD>
Predefined Objects
In JavaScript the following objects are
automatically created for you (always
available)
document
navigator
screen
window
The document Object Objects Hierarchy
Many attributes of the current document are JavaScript objects include object hierarchy +
(property or method)
available via the document object:
window.document.lastModified
title cookie window.document.clear()
URL images need not be fully qualified
forms links document.lastModified
(fg/bg)Color forms proceeds from most to least general
window.document.forms[0].inputText1.value
and more
all names are case sensitive
Objects Object Oriented The with Statement
Objects complex data types or containers that Establishes the default object for a set of
have both data and code
statements
Methods code or functions that work on an
object s properties Within the set of statements, any property
Properties data that are stored and retrieved via references that do not specify an object are
object references assumed to be for the default object
This is not true "OO" because the object hierarchy
is not extensible, you can create new objects, but
cannot extend existing ones
Example of with Dynamic HTML
var a, x, y
Java Java
var r=10 CSS Script Script
with (Math) {
HTML CSS
a = PI * r * r HTML HTML
x = r * cos(PI) HTML
y = r * sin(PI/2)
}
Dynamic HTML