1 Representation and Management of Data on the Internet.

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

Intro to Javascript CS Client Side Scripting CS380 2.
Introducing JavaScript
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
Java Script Session1 INTRODUCTION.
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
The Web Warrior Guide to Web Design Technologies
EIW: Javascript the Language1 The JavaScript Language.
1 Outline 13.1Introduction 13.2A Simple Program: Printing a Line of Text in a Web Page 13.3Another JavaScript Program: Adding Integers 13.4Memory Concepts.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Javascript Client-side scripting. Up to now  We've seen a little about how to control  content with HTML  presentation with CSS  Javascript is a language.
1 Browser Scripting JavaScript. 2 Dynamic HTML XHTML contentCSS style rules appearanceScriptingLanguage manipulate.
1 Representation and Management of Data on the Web Client Side Programming.
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
1 Browser Scripting JavaScript. 2 Introduction 3 Client-Server Architecture In a client-server architecture, computation is done either in the client.
PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  PHP is interpreted  PHP code is embedded into HTML code  interpreter.
2012 •••••••••••••••••••••••••••••••••• Summer WorkShop Mostafa Badr
Introduction to scripting
JavaScript: Control Structures September 27, 2005 Slides modified from Internet & World Wide Web: How to Program (3rd) edition. By Deitel, Deitel,
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Scripting Languages.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Netprog: JavaScript1 JavaScript Client-side dynamic documents.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
1 Lecture #6 Dynamic Web Documents HAIT Summer 2005 Shimrit Tzur-David.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Lecture 9 The Basics of JavaScript Boriana Koleva Room: C54
1 Representation and Management of Data on the Web Javascript.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
ALBERT WAVERING BOBBY SENG. Week 4: JavaScript  Quiz  Announcements/questions.
XP Tutorial 10New Perspectives on HTML and XHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial.
JavaScript - Basic Concepts Prepared and Presented by Hienvinh Nguyen, Afshin Tiraie.
Overview of Form and Javascript fundamentals. Brief matching exercise 1. This is the software that allows a user to access and view HTML documents 2.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Scripting and Interactivity 이병희
 2000 Deitel & Associates, Inc. All rights reserved. Outline 8.1Introduction 8.2A Simple Program: Printing a Line of Text in a Web Page 8.3Another JavaScript.
JavaScript, Fourth Edition
JS1-1 Introduction to JavaScript (JavaScript 1) Xingquan (Hill) Zhu
4. Javascript M. Udin Harun Al Rasyid, S.Kom, Ph.D Lab Jaringan Komputer (C-307) Desain.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
COP 3813 Intro to Internet Computing Prof. Roy Levow Lecture 4 JavaScript.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
Java Script. introduction Today’s web sites need to go much beyond HTML. browsing through a web site, to actually interact with the web site. The web.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
INTERNET APPLICATIONS CPIT405 JavaScript Instructor: Rasha AlOmari
Basic Objects. Math Object  Math.cos( x ), x in radians  Math.sqrt ( x )  Math.pow ( x, y )  Math.ceil( x )  etc.
1 Browser Scripting JavaScript. 2 Introduction 3 Client-Server Architecture In a client-server architecture, computation is done either in the client.
 2001 Prentice Hall, Inc. All rights reserved. Outline 1 JavaScript.
>> Introduction to JavaScript
Chapter 6 JavaScript: Introduction to Scripting
JavaScript Syntax and Semantics
4. Javascript Pemrograman Web I Program Studi Teknik Informatika
JavaScript.
14 A Brief Look at JavaScript and jQuery.
JavaScript an introduction.
WEB PROGRAMMING JavaScript.
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
JavaScript CS 4640 Programming Languages for Web Applications
Tutorial 10: Programming with javascript
JavaScript: Introduction to Scripting
JavaScript CS 4640 Programming Languages for Web Applications
Presentation transcript:

1 Representation and Management of Data on the Internet

2 Overview A "scripting" language for HTML pages Embed code in HTML pages so they are downloaded directly to browser 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

3 Overview (cont.) Scripts can manipulate "browser objects:" –HTML form elements –Images –Frames –etc. For security – cannot write to disk (when run on a client)

4 Abilities Generating HTML content dynamically Monitoring and responding to user events Validate forms before submission Manipulate HTTP cookies Interact with the frames and windows of the browser Customize pages to suit users

5 It is not Java Java : –compilation required –can create “stand alone” application –much more complex more commands more built-in functions object-oriented

Web browser HTML Page: …code..… Desktop access Internet HTML/HTTP TCP/IP HTML/HTTP TCP/IP Web (HTTP) Server HTML pages w/ embedded script Remote host built-in JavaScript interpreter Web Architecture for JavaScript "CLIENT""SERVER"

7 Example <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> An Hello World Example document.writeln(" Can't you find a better example than Hello World? );

8 The document will be written after the line, since the script is in the head

9 Past and Present Built into Netscape Navigator since v2.0 (early 1996) Developed independently of Java Proprietary, but submitted as standard and built into Microsoft IE 3.0 and later Standardized by ECMA (European Computer Manufacture’s Association) into ECMAscript EMCAscript joins JavaScript and Jscript to one standardEMCAscript

10 Client and Server JavaScript can be used –On the client side –On the server More lightweight and reliable on clients than Java (Applets) Useful for developing interactive interface (Dynamic HTML) Also useful for "gluing" Java applets together

11 CGI and other Server-side Architectures Strengths –allows access to server files and databases –makes no assumptions about client computer capabilities, puts little burden on it –easier to manage and control on server –more secure for client Weaknesses –puts most of processing load on server –requires round-trip for every submission, using valuable bandwidth –cannot provide instantaneous response expected with GUI –less secure for server

12 JavaScript Reserved Keywords break case continue delete do else false for function if in new null return switch this true typeof var void while with

13 Non Used Reserved Words catch class const debugger default enum export extends finally import super try

14 Javascript Variables Untyped! Can be declared with var keyword: var foo; Can be created automatically by assigning a value: foo = 1; thank = “ Thank for all the fish";

15 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

16 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

17 Literals The typical bunch: –Numbers –Strings“ Let it be ” –Boolean: true false –Arrays: [1, “ ab ba ”,17.234] –null Arrays can hold anything! You can use typeof(A) to get the type of A: number, string, object..

18 Operators Arithmetic, comparison, assignment, bit wise, Boolean (pretty much just like Java) + - * / % == != > = <= && || ! & | > += -= *= /= %=

19 Which is correct? Which of the following two is correct? What is the ‘type’ of the answer? x = “The answer is” + 42 y = 42 + “is the answer”

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) {...}

Boolean Operators and if (true && true) {…} or if (true || false) {…} not if (! false) {...}

22 Using Variables var firstNumber = 11, secondNumber = 23, sum; sum = firstNumber + secondNumber; document.write(" The sum of " + firstNumber + " and " + secondNumber + " is "); document.write(" " + sum + " ");

23

24 Control Structures Some just like Java: if if-else ?: switch for while do-while And a few not like in Java for (var in object) with (object)

JavaScript’s Basic Constructs sequence (block) condition (selection) loop (iteration)

JavaScript Constructs sequence (block) –executes with no conditions –semicolons optional using one statement per line, but not a bad thing to use all the time var metushelahAge = 130; var yourAverageAge yourAverageAge = metushelahAge - 98 var myObject = new Object("initial value") more statements here.. …..

JavaScript Constructs condition (selection) if (condition) {statements if true} else {statements if false} if (metushelahAge < yourAverageAge) { document.write (" its true that Metushelah is younger than most of you,") document.write (" computers never lie! ") }

JavaScript Constructs loop (iteration) –both for and while loops are available, e.g. for (init expression; condition; update expression){ statements } for (var i=0; i < inputAge.length; i++) { var oneChar = inputAge.substring (i, i+1) if (oneChar "9") { alert("Please enter a valid number “ + oneChar + " is not valid.") }

29 Loops Example for (var counter = 1 ; counter <= 8 ; ++counter) { document.write(“ Now with font size " + counter + " “); }

30

31 Javascript Functions The keyword function used to define a function (subroutine): function add(x,y) { return(x+y); }

32 Function Input and Outout 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

33

34 Functions Example 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) // base case return n; else return fibonacci( n - 1 ) + fibonacci( n - 2 ); }

35 Enter a number <INPUT TYPE = "button" VALUE = "Calculate" ONCLICK = "fibonacciValue()" Fibonacci Value <INPUT NAME = "result" TYPE = "text">

36 Global Functions (1) escape – changes characters in a string that are not in the ASCII characters set to HEX unescape – decodes the escape encoding eval – gets a string of JavaScript code, evaluates it and executes it –It allows dynamic code execution

37 Global Functions (2) isNaN – takes a numeric argument and returns true if the value is not a number parseFloat – takes a string argument and converts its beginning to a float number (or return NaN) parseInt – takes a string argument and converts its beginning to an integer number (or return NaN)

38 Global Functions (3) isFinite – given a numeric argument it returns true if the argument is not –NaN –Number.POSITIVE_INFINITY – Number.NEGATIVE_INFINITY

39 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()

40 Objects Are Like Arrays myCar.make = "Ford" myCar.model = "Mustang" myCar.year = 66; myCar[“make”] = "Ford" myCar[“model”] = "Mustang" myCar[“year”] = 66 ;

41 function show_props(obj, obj_name) { var result = "" for (var i in obj) result += obj_name + "." + i + " = " + obj[i] + "\n" return result } myCar.make = Ford myCar.model = Mustang myCar.year = 66 So, the function call show_props(myCar, "myCar") would return the following:

42 Creating a New Object There are two ways to create new objects: objectName = {prop1:val1, prop2:val2, …, propN:valN} Object Initializer Constructor function 1.Define a constructor function 2.Create the new object by new

43 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}}

44 Creating a Method A method of an object is a function that has been assigned to the object: object.methodName = functionName

45 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 } Setting the method

46 Eval Example function Dog(name,breed,color) { this.name=name this.breed=breed this.color=color } myDog = new Dog("Gabby") myDog.breed="Lab" var breed='Shepherd' document.write(" " + eval('breed')) document.write(" " + myDog.eval('breed'))

47 Eval Example function stone(str) { this.eval("this."+str) this.eval("this.y=43") this.z=44 this["z2"] = 45 } flint = new stone("x=42") document.write(" flint.x is " + flint.x) document.write(" flint.y is " + flint.y) document.write(" flint.z is " + flint.z) document.write(" flint.z2 is " + flint.z2)

48 Deleting an Object To delete an object just set the object reference to null When are objects that are not set to null being removed?

49 Array Objects Arrays are supported as objects Attribute length Methods include: concat, join, pop, push, reverse, sort Joins elements into a string Joins two arrays

50 Creating a New Array var a = [“red”, “blue”, “green”] –Allocates an array of 3 cells and initializes the values var b = new Array(5) –Allocates an array of 5 cells without initializing values var c = new Array() –Creates a new empty array

51 Array Example Code var a = [8,7,6,5]; for (i=0;i<a.length;i++) a[i] += 2; b = a.reverse();

52 Passing Arrays to Functions Arrays can be passed to functions as arguments The array is passed by call-by-reference The name of the array is given to the function

53 Arrays Example function start() { var colors = ["red", "blue", "green"] printArray(colors); } function printArray( colorsArray ) { // prints the array but also modifies it for (var i in colorsArray) { var c = colorsArray[i]; document.writeln(" " + c + " "); colorsArray[i] = "gray"; }

54

55 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]);

56 Other Object Types String : manipulation methods Math : trig, log, random numbers Date : date conversions RegExp : regular expressions Number : limits, conversion to string

57 Math Common Methods abs(x) round(x) ceil(x) floor(x) max(x, y) min(x, y) cos(x) sin(x) tan(x) exp(x) pow(x, y) sqrt(x) log(x) Math Also includes constants such as: Math.E, Math.PI

58 String Common Methods (1) charAt (index) charCodeAt(index) Concat(string) fromCharCode(value1, value2, …) indexOf(substring, index) lastIndexOf(substring, index) slice(start, end) split(string) substr(start, length) substring(start, end) toLowerCase() toUpperCase() toString() valueOf()

59 Methods that Generate HTML anchor(name) – wraps the source with – big() – wraps the source with – blink() – wraps with – bold() – wraps the source with – fixed() – wraps the source with –

60 More Methods that Generate HTML fontcolor(color) – wraps with – fontsize(size) – wraps with – italic() – wraps with – link(url) –

61 More Methods that Generate HTML small() – wraps the source with – strike() – wraps the source with – sub() – wraps the source with – sup() – wraps the source with –

62 Date Common Methods getDate(), getFullYear(), getMonth(), getDay getTime(), getHours(), getMinutes(), getSeconds(), getMilliseconds() All these have a version with UTC (e.g., getUTCDate()) for GMT (Greenwich Mean Time)

63 Arrays Example function getTimes() { var current = new Date(); var out = new String(); out = "Day: " + current.getDay()+"\n"; out = out.concat("Month: " + current.getMonth() + "\n"); out = out.concat("Year: " + current.getFullYear() + "\n"); out = out.concat("GMT Time: " + current.toUTCString() + "\n"); out = out.concat("Time: " + current.toString() + "\n"); timesForm.output.value = out; }

64

65

66 Predefined Objects In JavaScript the following objects are automatically created for you (always available) –document –navigator –screen –window

67 The document Object Many attributes of the current document are available via the document object: TitleReferrer URLImages FormsLinks Colors

68 document write method document.write() like a print statement – the output goes into the HTML document document.write("My title is" + document.title); string concatenation

69 Objects Hierarchy JavaScript objects include object hierarchy + (property or method) –window.document.lastModified –metushelahBirthday.getYear() need not be fully qualified –document.lastModified proceeds from most to least general –window.document.forms[0].inputText1.value all names are case sensitive

70 Objects  Object Oriented Objects – complex data types or “containers” that have both data and code Methods – code or “functions” that work on an object’s properties Properties – data that are stored and retrieved via object references This is not true "OO" because the object hierarchy is not extensible, you can create new objects, but cannot extend existing ones

71 The with Statement Establishes the default object for a set of statements Within the set of statements, any property references that do not specify an object are assumed to be for the default object

72 Example of with var a, x, y var r=10 with (Math) { a = PI * r * r x = r * cos(PI) y = r * sin(PI/2) }

73 Dynamic HTML HTML CSS Java Script HTML Dynamic HTML HTML CSS Java Script