86
1 Course Notes for Course Notes for CS1520 CS1520 Programming Languages Programming Languages Part B Part B By By John C. Ramirez / Wonsun Ahn John C. Ramirez / Wonsun Ahn Department of Computer Science Department of Computer Science University of Pittsburgh University of Pittsburgh

1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Embed Size (px)

Citation preview

Page 1: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

1

Course Notes forCourse Notes for

CS1520 CS1520 Programming Programming

LanguagesLanguagesPart BPart B

ByByJohn C. Ramirez / Wonsun AhnJohn C. Ramirez / Wonsun Ahn

Department of Computer ScienceDepartment of Computer ScienceUniversity of PittsburghUniversity of Pittsburgh

Page 2: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

2

• These notes are intended for use by students in CS1520 at These notes are intended for use by students in CS1520 at the University of Pittsburgh and no one elsethe University of Pittsburgh and no one else

• These notes are provided free of charge and may not be sold These notes are provided free of charge and may not be sold in any shape or formin any shape or form

• Material from these notes is obtained from various sources, Material from these notes is obtained from various sources, including, but not limited to, the following:including, but not limited to, the following:

4 Programming the World Wide Web, multiple editions, by Robert Programming the World Wide Web, multiple editions, by Robert Sebesta (AW)Sebesta (AW)

4 JavaScript by Don Gossein (Thomson Learning)JavaScript by Don Gossein (Thomson Learning)

4 https://developer.mozilla.org/en/JavaScript/Reference

4 http://www.w3schools.com/jsref/default.asp

4 http://www.w3.org/TR/XMLHttpRequest/

Page 3: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

3

Lecture 1: Intro to JavaScriptLecture 1: Intro to JavaScript

• What is JavaScript?What is JavaScript?

4 Language developed by NetscapeLanguage developed by Netscape

4 Java is to JavaScript what car is to carpetJava is to JavaScript what car is to carpet

4 Primary purpose is for "client-end" Primary purpose is for "client-end" processing of HTML documentsprocessing of HTML documents• JavaScript code is embedded within the JavaScript code is embedded within the

html of a documenthtml of a document

• An interpreter in the browser interprets An interpreter in the browser interprets the JavaScript code when appropriatethe JavaScript code when appropriate

• Can add Can add dynamic contentdynamic content to a Web page to a Web page

Page 4: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

4

Lecture 1: JavaScript BasicsLecture 1: JavaScript Basics

• How to include JavaScript in html?How to include JavaScript in html?

4 JavaScript programs require the JavaScript programs require the <SCRIPT> tag in .html files<SCRIPT> tag in .html files

<script type = "text/javascript"><script type = "text/javascript">

ACTUAL JavaScript code hereACTUAL JavaScript code here

</script></script>

4 These can appear in either the <HEAD> These can appear in either the <HEAD> or <BODY> section of an html documentor <BODY> section of an html document• Event handlers and functions are Event handlers and functions are

typically placed in the <HEAD>typically placed in the <HEAD>– Easier to read / maintainEasier to read / maintain– Events may fire before page completes Events may fire before page completes

loadingloading

Page 5: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

5

Lecture 1: JavaScript BasicsLecture 1: JavaScript Basics

• Code that needs to execute during loading Code that needs to execute during loading of the HTML page placed in <BODY>of the HTML page placed in <BODY>

– Preferably at end to speed up loading of contentPreferably at end to speed up loading of content

4 Some browsers may not support scripting Some browsers may not support scripting (i.e. have it turned off)(i.e. have it turned off)• To be safe, you could put your scripts in To be safe, you could put your scripts in

html comments as specified in Sebesta texthtml comments as specified in Sebesta text– This way browsers that do not recognize This way browsers that do not recognize

JavaScript will look at the programs as JavaScript will look at the programs as commentscomments

4 Note that, unlike PHP scripts, JavaScripts Note that, unlike PHP scripts, JavaScripts are are visible in the client browservisible in the client browser• Since they are typically acting only on the Since they are typically acting only on the

client, this is not a problemclient, this is not a problem

Page 6: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

6

Lecture 1: JavaScript BasicsLecture 1: JavaScript Basics

4 However, if we want to prevent the script However, if we want to prevent the script itself from being (easily) seen, we can itself from being (easily) seen, we can upload our JavaScript from a fileupload our JavaScript from a file• This will show only the upload tag in our This will show only the upload tag in our

final document, not the JavaScript from final document, not the JavaScript from the filethe file

• Use the src option in the tagUse the src option in the tag<script type = "text/javascript" src = <script type = "text/javascript" src = "bogus.js"></script>"bogus.js"></script>

– However, the source is still not really hiddenHowever, the source is still not really hidden– In a temp folder somewhere on computerIn a temp folder somewhere on computer

• Rather JS source separation is done for:Rather JS source separation is done for:– Ease of programming / maintenanceEase of programming / maintenance– Performance (JavaScript file can be cached)Performance (JavaScript file can be cached)

Page 7: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

7

Lecture 1: Simple ExampleLecture 1: Simple Example

<HTML><HTML><HEAD><HEAD><TITLE>First JavaScript Example</TITLE><TITLE>First JavaScript Example</TITLE></HEAD></HEAD><BODY><BODY><H2>This line is straight HTML</H2><H2>This line is straight HTML</H2><H3><H3><SCRIPT type = "text/javascript"><SCRIPT type = "text/javascript"> document.write("These lines are produced by<br/>");document.write("These lines are produced by<br/>"); document.write("the JavaScript program<br/>");document.write("the JavaScript program<br/>"); alert("Hey, JavaScript is fun!");alert("Hey, JavaScript is fun!");</SCRIPT></SCRIPT></H3></H3><H2>More straight HTML</H2><H2>More straight HTML</H2><SCRIPT type = "text/javascript" src="bogus.js"></script><SCRIPT type = "text/javascript" src="bogus.js"></script></BODY></BODY></HTML></HTML>

Page 8: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

8

Lecture 1: JavaScript VariablesLecture 1: JavaScript Variables

4 JavaScript variables have no typesJavaScript variables have no types• Type is Type is determined dynamicallydetermined dynamically, based on the , based on the

value storedvalue stored– This is becoming familiar!This is becoming familiar!– The The typeoftypeof operator can be used to check type operator can be used to check type

4 Declarations are made using the Declarations are made using the varvar keyword keyword• Declarations Declarations outsideoutside of any of any functionfunction are are globalglobal

• Declarations Declarations withinwithin a a functionfunction are are locallocal to that to that functionfunction

• Can be implicitly declared, but not advisableCan be implicitly declared, but not advisable

• Variables declared but not initialized have the Variables declared but not initialized have the value value undefinedundefined

Page 9: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

9

Lecture 1: JavaScript VariablesLecture 1: JavaScript Variables

4 Variables are either:Variables are either:• Primitive valuesPrimitive values

– numbers, booleans, strings, undefined, nullnumbers, booleans, strings, undefined, null

• References to objects or arraysReferences to objects or arrays– Like Java (but not like PHP)Like Java (but not like PHP)

• Everything is (or can be) an objectEverything is (or can be) an object

4 Variable identifiers are similar to those in Variable identifiers are similar to those in other languages (ex: Java)other languages (ex: Java)• Cannot use a keywordCannot use a keyword

• Must begin with a letter, $, or _Must begin with a letter, $, or _– Followed by any sequence of letters, $, _ or Followed by any sequence of letters, $, _ or

digitsdigits

• Case sensitiveCase sensitive

Page 10: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

10

Lecture 1: JavaScript ExpressionsLecture 1: JavaScript Expressions

4 Numeric operators in JavaScript are Numeric operators in JavaScript are similar to those in most languagessimilar to those in most languages

+, –, *, /, %, ++, --+, –, *, /, %, ++, --

• Precedence and associativity are also Precedence and associativity are also fairly standardfairly standard

4 StringsStrings• Have the + operator for concatenationHave the + operator for concatenation

• Have a number of methods to do typical Have a number of methods to do typical string operationsstring operations

– charAt, indexOf, toLowerCase, substringcharAt, indexOf, toLowerCase, substring

• Looks kind of like Java – intentionallyLooks kind of like Java – intentionally

Page 11: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

11

Lecture 1: JavaScript ExpressionsLecture 1: JavaScript Expressions

4 Similar to PHP, with mixed number/string Similar to PHP, with mixed number/string type expressions, JavaScript will coerce if type expressions, JavaScript will coerce if it canit can• If operator is + and an operand is string, it If operator is + and an operand is string, it

will always coerce other to stringwill always coerce other to string

• If operator is arithmetic, and string value If operator is arithmetic, and string value can be coerced to a number it will do socan be coerced to a number it will do so

– If string is non-numeric, result is NaN If string is non-numeric, result is NaN (NotaNumber)(NotaNumber)

• We can also explicitly convert the string to We can also explicitly convert the string to a number using parseInt and parseFloata number using parseInt and parseFloat

– Again looks like JavaAgain looks like Java

4 See ex2.htmlSee ex2.html

Page 12: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

12

Lecture 1: Control StatementsLecture 1: Control Statements

• Relational operators:Relational operators:==, !=, <, >, <=, >===, !=, <, >, <=, >=

• The above allow for type coercion. To The above allow for type coercion. To prevent coercion there is alsoprevent coercion there is also

===, !=====, !==– Similar to PHPSimilar to PHP

• Boolean operatorsBoolean operators&&, ||, !&&, ||, !

• &&, || are short-circuited (as in Java and &&, || are short-circuited (as in Java and PHP)PHP)

– DiscussDiscuss

Page 13: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

13

Lecture 1: Control StatementsLecture 1: Control Statements

• Control statements similar to JavaControl statements similar to Java4 if, while, do, for, switchif, while, do, for, switch

• Variables declared in for loop header are Variables declared in for loop header are not local to that loop (hoisted to top of not local to that loop (hoisted to top of function)function)

• FunctionsFunctions4 Similar to Java functions, butSimilar to Java functions, but

• Header is somewhat differentHeader is somewhat differentfunction name(paramfunction name(param__list)list)– Return type not specified (like PHP, since JS Return type not specified (like PHP, since JS

has dynamic typing)has dynamic typing)– Param types also not specifiedParam types also not specified

Page 14: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

14

Lecture 1: FunctionsLecture 1: Functions

• Functions execute when they are called, Functions execute when they are called, just as in any languagejust as in any language

• To allow this, function code should be in To allow this, function code should be in the <HEAD> section of the .html filethe <HEAD> section of the .html file

• Variables declared in a function are local to Variables declared in a function are local to the functionthe function

• Parameters are all Parameters are all valuevalue– No parameter type-checkingNo parameter type-checking– Numbers of formal and actual parameters do Numbers of formal and actual parameters do

not have to correspondnot have to correspond» Extra actual parameters are ignoredExtra actual parameters are ignored» Extra formal parameters are undefinedExtra formal parameters are undefined

– All actual parameters can be accessed All actual parameters can be accessed regardless of formal parameters by using the regardless of formal parameters by using the argumentsarguments array array

• See ex3.htmlSee ex3.html

Page 15: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

15

Lecture 1: JavaScript ObjectsLecture 1: JavaScript Objects

• JavaScript is an JavaScript is an object-basedobject-based language language4 NO classes NO classes (also known as duck typing)(also known as duck typing)

• An object is just a bunch of member An object is just a bunch of member propertiesproperties

• The set of properties can change at any The set of properties can change at any moment moment

4 Not object-oriented in the traditional senseNot object-oriented in the traditional sense

4 Does not support some features deemed Does not support some features deemed necessary for object-oriented languagesnecessary for object-oriented languages• Class inheritance not supported properlyClass inheritance not supported properly

– They can be They can be ““emulatedemulated”” but not perfectly but not perfectly– http://www.webreference.com/js/column79/

Page 16: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

16

Lecture 1: JavaScript ObjectsLecture 1: JavaScript Objects

4 JavaScript JavaScript objectsobjects are nothing more than are nothing more than property-valueproperty-value pairs pairs• Similar to associative arrays (hashes) in PHPSimilar to associative arrays (hashes) in PHP

• The object is analogous to the array, and The object is analogous to the array, and the properties are analogous to the keysthe properties are analogous to the keys

• Ex:Ex:var my_tv = new Object();var my_tv = new Object();my_tv.brand = “Samsung”;my_tv.brand = “Samsung”;my_tv.size = 46;my_tv.size = 46;my_tv.jacks = new Object();my_tv.jacks = new Object();my_tv.jacks.input = 5;my_tv.jacks.input = 5;my_tv.jacks.output = 2;my_tv.jacks.output = 2;

Page 17: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

17

Lecture 1: JavaScript ObjectsLecture 1: JavaScript Objects

• Objects can be accessed like associative arrays Objects can be accessed like associative arrays tootoo

• The previous code is equivalent to:The previous code is equivalent to:var my_tv = {};var my_tv = {};my_tv[“brand”] = “Samsung”;my_tv[“brand”] = “Samsung”;my_tv[“size”] = 46;my_tv[“size”] = 46;my_tv[“jacks”] = {};my_tv[“jacks”] = {};my_tv[“jacks”][“input”] = 5;my_tv[“jacks”][“input”] = 5;my_tv[“jacks”][“output”] = 2;my_tv[“jacks”][“output”] = 2;

• Which is equivalent to using an object literal:Which is equivalent to using an object literal:var my_tv = {brand: “Samsung”, size: 46, jacks: var my_tv = {brand: “Samsung”, size: 46, jacks: {input: 5, output: 2}};{input: 5, output: 2}};

document.write(my_tv.brand);// “Samsung”document.write(my_tv.brand);// “Samsung”

• Internally in the interpreter, JavaScript objects are Internally in the interpreter, JavaScript objects are actually organized as hashes just like PHP arraysactually organized as hashes just like PHP arrays

Page 18: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

18

Lecture 1: JavaScript ObjectsLecture 1: JavaScript Objects

• Also, objects all have the same data type – Also, objects all have the same data type – objectobject

• We can write We can write constructor functionsconstructor functions for for objects if we'd like, but these do not create objects if we'd like, but these do not create new data types – just easy ways of new data types – just easy ways of uniformly initializing objectsuniformly initializing objectsfunction TV(brand, size, injacks, outjacks)function TV(brand, size, injacks, outjacks){{ this.brand = brand;this.brand = brand; this.size = size;this.size = size; this.jacks = new Object();this.jacks = new Object(); this.jacks.input = injacks;this.jacks.input = injacks; this.jacks.output = outjacks;this.jacks.output = outjacks;}}……var my_tv = new TV(”Samsung”, 46, 5, 2);var my_tv = new TV(”Samsung”, 46, 5, 2);

Page 19: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

19

Lecture 1: JavaScript ObjectsLecture 1: JavaScript Objects

– – Which is actually exactly equivalent to:Which is actually exactly equivalent to:var my_tv = {brand: “Samsung”, size: 46, jacks: var my_tv = {brand: “Samsung”, size: 46, jacks: {input: 5, output: 2}};{input: 5, output: 2}};

– – Except for prototype inheritanceExcept for prototype inheritance (More on that later when we talk about (More on that later when we talk about inheritance)inheritance)

Page 20: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

20

Lecture 1: JavaScript ObjectsLecture 1: JavaScript Objects

• Once an object is constructed, I can change its Once an object is constructed, I can change its properties if I want to (since it’s just a keyed properties if I want to (since it’s just a keyed array)array)

– LetLet’’s say I want to add a method to my TV called s say I want to add a method to my TV called "show_properties""show_properties"

function show_properties(){ document.write("Here is your TV: <BR/>"); document.write("Brand: ", this.brand,"<BR/>"); document.write("Size: ", this.size, "<BR/>"); document.write("Input Jacks: "); document.write(this.jacks.input, "<BR/>"); document.write("Output Jacks: "); document.write(this.jacks.output, "<BR/>");}

my_tv.show = show_properties;;

– See ex4.htmlSee ex4.html

Page 21: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 1: Javascript ObjectsLecture 1: Javascript Objects

• We can do a lot with Javascript We can do a lot with Javascript objectsobjects4 Even though Javascript is not truly Even though Javascript is not truly

object-oriented, we can still do some object-oriented, we can still do some OOPOOP• Encapsulating data and methods in Encapsulating data and methods in

objectsobjects

• Using methods for operations on the Using methods for operations on the objectsobjects

• Implement inheritance using prototypesImplement inheritance using prototypes

• See ex5.htmlSee ex5.html

21

Page 22: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 1: Javascript ObjectsLecture 1: Javascript Objects

• But how about inheritance?But how about inheritance?4 C++ or Java uses types to do inheritanceC++ or Java uses types to do inheritance

• Using parent classes and child classesUsing parent classes and child classes

4 JavaScript has no classesJavaScript has no classes

Uses something called Uses something called prototypeprototype objects objects

4 Prototype objectsPrototype objects• Can be thought of “parent objects”Can be thought of “parent objects”

• Associated with a constructor functionAssociated with a constructor function

• Serve similar purposes as parent classesServe similar purposes as parent classes

• Regular objects just like all other objectsRegular objects just like all other objects

22

Page 23: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 1: Javascript ObjectsLecture 1: Javascript Objects

// Create “parent” objectfunction foo() { … };foo.prototype.x = 11;// Create “child” objectvar o = new foo();// Access “parent” propertydocument.write(o.x); // 11

// Create “parent” objectfunction foo() { … };foo.prototype.x = 11;// Create “child” objectvar o = new foo();// Access “parent” propertydocument.write(o.x); // 11

x: 11

1. Create function foo (implicitly creates “parent” foo.prototype)

2. Create “child” o by calling foo (o inherits from foo.prototype)

3. Access “parent” property x in foo.prototype through inheritance

Careful. One prototype object is shared by all children objects.1. Updating parent property will change it for all children objects.2. Hence prototypes almost exclusively store only methods or

constants

inherit

prototype:

23

Page 24: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

User Created Objects

Built-in Prototype Objects

… = new Object()

… = function() {}

… = new Array()

Lecture 1: Javascript ObjectsLecture 1: Javascript Objects

O2O1

Object.prototype

BarFoo

Function.prototype

A2A1

Array.prototype

NULL

24

• There are built-in prototype objects for each native object There are built-in prototype objects for each native object constructorconstructor4 Array, Number, String, Boolean, FunctionArray, Number, String, Boolean, Function

Page 25: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

25

Lecture 1: Array ObjectsLecture 1: Array Objects

4 Arrays: more relaxed version of Java arraysArrays: more relaxed version of Java arrays• Size can be changed and data can be mixedSize can be changed and data can be mixed• Cannot use arbitrary keys as with PHP Cannot use arbitrary keys as with PHP

arraysarrays– Non-numerical keys access the properties of the Non-numerical keys access the properties of the

array object and are not be counted as elementsarray object and are not be counted as elements

4 Creating arraysCreating arrays• Using the new operator and a constructor Using the new operator and a constructor

with multiple argumentswith multiple argumentsvar A = new Array("hello", 2, "you");var A = new Array("hello", 2, "you");

• Using the new operator and a constructor Using the new operator and a constructor with a single numeric argumentwith a single numeric argument

var B = new Array(50);var B = new Array(50);

• Using square brackets to make a literalUsing square brackets to make a literalvar C = ["we", "can", 50, "mix", 3.5, "types"];var C = ["we", "can", 50, "mix", 3.5, "types"];

Page 26: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

26

Lecture 1: Array ObjectsLecture 1: Array Objects

4 Array LengthArray Length• Like Java, length is an attribute of all array Like Java, length is an attribute of all array

objects (not the Array.prototype object)objects (not the Array.prototype object)

• However, in Javascript it does not However, in Javascript it does not necessarily represent the number of items necessarily represent the number of items in the arrayin the array

– 1 + (last index in array with assigned value)1 + (last index in array with assigned value)

• Length can even be changed by Length can even be changed by programmerprogrammer

• Actual memory allocation is dynamic and Actual memory allocation is dynamic and occurs when necessaryoccurs when necessary

– An array with length = 1234 may in fact have An array with length = 1234 may in fact have memory allocated for only a few elementsmemory allocated for only a few elements

– When accessed, empty elements are undefinedWhen accessed, empty elements are undefined

Page 27: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

27

Lecture 1: Array ObjectsLecture 1: Array Objects

• Array MethodsArray Methods4 There are a number of predefined operations There are a number of predefined operations

in Array.prototype that are inherited by all in Array.prototype that are inherited by all arraysarrays

– concatconcat two arrays into one two arrays into one– joinjoin array items into a single string (commas array items into a single string (commas

between)between)– push, pop, shift, unshiftpush, pop, shift, unshift

» Push and pop are a "right stack"Push and pop are a "right stack"» Shift and unshift are a "left stack"Shift and unshift are a "left stack"

– sortsort» Sort by default compares using alphabetical orderSort by default compares using alphabetical order» To sort using numbers we pass in a comparison To sort using numbers we pass in a comparison

function defining how the numbers will be comparedfunction defining how the numbers will be compared– reversereverse

» Reverse the items in an arrayReverse the items in an array

Page 28: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

28

Lecture 1: Array ObjectsLecture 1: Array Objects

• These operations are invoked via These operations are invoked via method calls, in an object-based waymethod calls, in an object-based way

– Also many, such as Also many, such as sortsort and and reversereverse are are mutatorsmutators, affecting the array itself, affecting the array itself

4 JavaScript also has 2-dimensional JavaScript also has 2-dimensional arraysarrays• Created as arrays of arraysCreated as arrays of arrays

4 see ex6.html see ex6.html

Page 29: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

29

Lecture 1: Regular ExpressionsLecture 1: Regular Expressions

4 JavaScript regular expression handling is JavaScript regular expression handling is also based on that in Perlalso based on that in Perl• The patterns and matching procedures are The patterns and matching procedures are

the same as in Perl, Java and PHP (PCRE)the same as in Perl, Java and PHP (PCRE)• However, now the functions are methods However, now the functions are methods

within a string object (similar to Java)within a string object (similar to Java)var s = "a man, a plan, a canal: panama";var s = "a man, a plan, a canal: panama";var loc = s.search(/plan/);var loc = s.search(/plan/);var matches1 = s.match(/an/g);var matches1 = s.match(/an/g);var matches2 = s.match(/\w+/g);var matches2 = s.match(/\w+/g);var matches3 = s.split(/\W+/);var matches3 = s.split(/\W+/);s = s.replace(/\W/g, "-");s = s.replace(/\W/g, "-");– Note that match is similar to the PHP match Note that match is similar to the PHP match

functionfunction» Returns the matched pieces as opposed to the Returns the matched pieces as opposed to the

non-matched pieces (that split returns)non-matched pieces (that split returns)

• See ex7.htmlSee ex7.html

Page 30: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

30

Lecture 1: DebuggingLecture 1: Debugging

4 Special note on JavaScript debuggingSpecial note on JavaScript debugging• If there is a syntax error in your codeIf there is a syntax error in your code

– JavaScript will just refuse to execute it and JavaScript will just refuse to execute it and show a blank page on the web browsershow a blank page on the web browser

– Similar to the default behavior of PHPSimilar to the default behavior of PHP

• What to do?What to do?• Popular browsers have diagnostic tools:Popular browsers have diagnostic tools:

– Safari: Web InspectorSafari: Web Inspector– Firefox: Firebug Extension (Firefox: Firebug Extension (http://

getfirebug.com)– They also have debuggers with breakpointsThey also have debuggers with breakpoints

• Use JavaScript LintUse JavaScript Lint– http://www.javascriptlint.com/

Page 31: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

31

Lecture 2: DOMLecture 2: DOM

• The The DDocument ocument OObject bject MModelodel4 Developed by W3C (World-Wide Web Consortium)Developed by W3C (World-Wide Web Consortium)

• http://www.w3c.org/DOM/

4 Specifies the contents of Web documents in an Specifies the contents of Web documents in an object-oriented wayobject-oriented way• Allows programming languages to access and Allows programming languages to access and

manipulate the components of documentsmanipulate the components of documents

• Defined at a high level so that a variety of Defined at a high level so that a variety of languages can be used with itlanguages can be used with it

• It is still being updated / revisedIt is still being updated / revised

4 We are not even scratching the surface here We are not even scratching the surface here

Page 32: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 2: DOMLecture 2: DOM

• History / IdeaHistory / Idea4 HTML and XML documents consist of tagsHTML and XML documents consist of tags

4 Well-formatted documents (required in Well-formatted documents (required in XHTML and XML) can be viewed as a treeXHTML and XML) can be viewed as a tree• Ex: Ex:

http://www.w3schools.com/htmldom/default.asp

4 DOM provides a language-independent, DOM provides a language-independent, object-based model for accessing / object-based model for accessing / modifying and adding to these tagsmodifying and adding to these tags

4 DOM 0DOM 0• Not formally specified by W3C but includes Not formally specified by W3C but includes

a lot of useful functionalitya lot of useful functionality32

Page 33: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 2: DOMLecture 2: DOM

4 DOM 1, 2, 3DOM 1, 2, 3• Formal specifications of model and Formal specifications of model and

functionalityfunctionality

• Each builds on / improves previousEach builds on / improves previous

4 Unfortunately there are still Unfortunately there are still compatibility issues with browserscompatibility issues with browsers• IE through IE8 does not fully support IE through IE8 does not fully support

DOM 2DOM 2– It has its own syntax for event attachmentIt has its own syntax for event attachment

• IE9 does support DOM 2 but until all IE9 does support DOM 2 but until all older versions go away the problem still older versions go away the problem still existsexists

33

Page 34: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

34

Lecture 2: EventsLecture 2: Events

4 With documents DOM specifies With documents DOM specifies eventsevents and and event handlersevent handlers• Different parts of a document have different Different parts of a document have different

events associated with themevents associated with them

• We can define handlers to react to these We can define handlers to react to these eventsevents

4 These allow us to "interact" with and add These allow us to "interact" with and add "dynamic content" to web documents"dynamic content" to web documents• Ex: Can preprocess form elementsEx: Can preprocess form elements

• Ex: Can load / update / change what is Ex: Can load / update / change what is displayed in response to an eventdisplayed in response to an event

Page 35: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

35

Lecture 2: DOM and EventsLecture 2: DOM and Events

• documentdocument refers to the top-level document refers to the top-level document4 Each document has access to its properties and Each document has access to its properties and

to the components that are declared within itto the components that are declared within it• Ex: title, URL, forms[], applets[], images[]Ex: title, URL, forms[], applets[], images[]

• Attributes with IDs can also be specified by ID Attributes with IDs can also be specified by ID (from DOM 1)(from DOM 1)

4 Once we know the components, events and Once we know the components, events and event-handlers, we can write JavaScript event-handlers, we can write JavaScript programs to process Web pages on the programs to process Web pages on the client-client-sideside• Client computers are typically less busy than Client computers are typically less busy than

servers, so whatever we can do at the client will be servers, so whatever we can do at the client will be helpful overall and result in faster responsehelpful overall and result in faster response

Page 36: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

36

Lecture 2: DOM and EventsLecture 2: DOM and Events

– Ex: Checking form correctness before it is Ex: Checking form correctness before it is submitted submitted

4 In HTML documents events are specified In HTML documents events are specified through through tag attributestag attributes• Within the tag identifying an HTML Within the tag identifying an HTML

component, we can specify in an attribute component, we can specify in an attribute how the component reacts to various eventshow the component reacts to various events

4 See Sebesta Table 5.1 for events and tag See Sebesta Table 5.1 for events and tag attributes and Table 5.2 for the tags that attributes and Table 5.2 for the tags that have a given attributehave a given attribute

4 Similar in idea to Java, we assign event Similar in idea to Java, we assign event handling code to the tag attributes, and the handling code to the tag attributes, and the code executes when the event occurscode executes when the event occurs

Page 37: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 2: EventsLecture 2: Events

• We can also attach events in JavascriptWe can also attach events in Javascript4 In DOM 0, events are attached in an In DOM 0, events are attached in an ““inlineinline”” way: way:

• Ex: Ex: theElement.onclick = functionNametheElement.onclick = functionName

4 In DOM 2, a more flexible event model was In DOM 2, a more flexible event model was developed, so that more than one handler could developed, so that more than one handler could be attached to the same event:be attached to the same event:• Ex: Ex: theElement.addEventListener(type, fn, opt)theElement.addEventListener(type, fn, opt)

– Where opt is a boolean to determine if the event is Where opt is a boolean to determine if the event is ““capturedcaptured”” or or ““bubblesbubbles””

» See: See: http://en.wikipedia.org/wiki/DOM_Events

• Unfortunately, IE (up through IE8) does not use Unfortunately, IE (up through IE8) does not use DOM 2DOM 2

– It has its own, similar model It has its own, similar model

37

Page 38: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

38

Lecture 2: DOM and EventsLecture 2: DOM and Events

4 Ex: Event Ex: Event mouseovermouseover occurs when the occurs when the mouse is place over a displayed elementmouse is place over a displayed element• Elements that allow for the mouseover Elements that allow for the mouseover

event have the attribute event have the attribute onmouseoveronmouseover

• In HTML or Javascript, the programmer In HTML or Javascript, the programmer assigns a function call to the attribute, so assigns a function call to the attribute, so that when the event occurs the function that when the event occurs the function is calledis called

<input type = "radio" name = "choice" value = "1" <input type = "radio" name = "choice" value = "1" onmouseover = "showChoice(1)">onmouseover = "showChoice(1)">

• We can define showChoice however we'd We can define showChoice however we'd likelike

– ex: alert("You are about to choose Choice 1"); ex: alert("You are about to choose Choice 1");

Page 39: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

39

Lecture 2: Example: Pre-processing a FormLecture 2: Example: Pre-processing a Form

• A very common client-side A very common client-side operation is pre-processing a formoperation is pre-processing a form4 Ensure that fields are filled and Ensure that fields are filled and

formatted correctly, so server does not formatted correctly, so server does not have tohave to• Saves load on the server, saves time Saves load on the server, saves time

and saves bandwidthand saves bandwidth

• We can check a form overall by using We can check a form overall by using the attribute the attribute onsubmitonsubmit

– We can put it right into the form as an We can put it right into the form as an attributeattribute

– Or we can assign the attribute through the Or we can assign the attribute through the document object in Javascriptdocument object in Javascript

Page 40: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

40

Lecture 2: Example: Pre-processing a formLecture 2: Example: Pre-processing a form

• We can check individual components as We can check individual components as they are entered as wellthey are entered as well

– Ex: <input type = "text"> has the Ex: <input type = "text"> has the onchangeonchange attributeattribute

» Triggered when contents are changed and Triggered when contents are changed and focus changesfocus changes

– Ex: <input type = "radio"> has the Ex: <input type = "radio"> has the onclickonclick attributeattribute

» Triggered when the radio button is clicked Triggered when the radio button is clicked with the mousewith the mouse

• See ex8.htmlSee ex8.html– Note: Script to process this form is not Note: Script to process this form is not

shownshown– You may want to write it as an exerciseYou may want to write it as an exercise

Page 41: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

41

Lecture 3: Processing Multiple Forms and Multiple SubmitsLecture 3: Processing Multiple Forms and Multiple Submits

4 Web pages can also have multiple formsWeb pages can also have multiple forms• These can be handled both on the client These can be handled both on the client

side using JavaScript and on the server side using JavaScript and on the server sideside

• Idea is to identify which form has been Idea is to identify which form has been submitted and respond accordinglysubmitted and respond accordingly

– See mform.html and mform.phpSee mform.html and mform.php

4 Similarly, we can have multiple submits Similarly, we can have multiple submits of a single formof a single form• See also msub.html and msub.phpSee also msub.html and msub.php

4 One more example demonstrating DOMOne more example demonstrating DOM• See ex9.htmlSee ex9.html

Page 42: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

42

Lecture 3: AJAXLecture 3: AJAX

• AAsynchronous synchronous JJavaScript avaScript AAnd nd XXMLML• This is technique that was coined in This is technique that was coined in

Feb. 2005 but that has been used (more Feb. 2005 but that has been used (more or less) for quite a while before thator less) for quite a while before that

• It allows the client and the server to It allows the client and the server to communicate without requiring a "hard" communicate without requiring a "hard" submit and page refreshsubmit and page refresh

– In particular, the page can be updated In particular, the page can be updated without reloading it in its entiretywithout reloading it in its entirety

• Makes the user interface for a Web app. Makes the user interface for a Web app. appearappear more like that of a desktop app more like that of a desktop app

• See: See: http://en.wikipedia.org/wiki/AJAX http://developer.mozilla.org/en/docs/AJAX

Page 43: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

43

Lecture 3: AJAXLecture 3: AJAX

4 Let's look at a few details and some Let's look at a few details and some simple examplessimple examples• You may also want to research it on your You may also want to research it on your

own own

4 AJAX centers around the AJAX centers around the XMLHttpRequestXMLHttpRequest objectobject

4 This object allows the client to connect to This object allows the client to connect to a server and to respond to the reply once a server and to respond to the reply once it has become availableit has become available

4 There is a lot that can be done with this, There is a lot that can be done with this, especially in conjunction with especially in conjunction with XMLXML and and JSONJSON – we will mention these later – we will mention these later

Page 44: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

44

Lecture 3: AJAXLecture 3: AJAX

4 It is a bit tricky to use, and is not consistent It is a bit tricky to use, and is not consistent across all browsers (esp. older versions)across all browsers (esp. older versions)

4 However, once you get the hang of it, it can However, once you get the hang of it, it can be a very useful tool and it is be a very useful tool and it is REALLY REALLY COOL!COOL!

4 Basic Idea:Basic Idea:• Programmer creates an instance of an Programmer creates an instance of an

XMLHttpRequestXMLHttpRequest object object

• Several useful attributes and methods are Several useful attributes and methods are associated with this object: associated with this object:

– see:see: http://www.w3.org/TR/XMLHttpRequest/

– Let's look at a few of them to see how they work Let's look at a few of them to see how they work together together

Page 45: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

45

Lecture 3: AJAXLecture 3: AJAX

• onreadystatechangeonreadystatechange– Attribute to which we assign an EventListener Attribute to which we assign an EventListener

(which is a function callback)(which is a function callback)– This will associate the function with the This will associate the function with the

occurrence of the readystatechange eventoccurrence of the readystatechange event» This event fires in several places, throughout This event fires in several places, throughout

the the execution (each time the state changes)the the execution (each time the state changes)» We can check the readyState to see what, if We can check the readyState to see what, if

anything, we will do in response – more on this anything, we will do in response – more on this soonsoon

• open(open(methodmethod, , urlurl, , asyncasync))» Where "method" is an HTTP methodWhere "method" is an HTTP method» Where "url" is the location of the serverWhere "url" is the location of the server» Where "async" is a boolean to determine if the Where "async" is a boolean to determine if the

transfer is to be done asynchronously or nottransfer is to be done asynchronously or not– Method to switch the object to the open state Method to switch the object to the open state

– i.e. get ready to send data to the server– i.e. get ready to send data to the server

Page 46: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

46

Lecture 3: AJAXLecture 3: AJAX

• send(data)send(data)» Where "data" is a the information to be sent to Where "data" is a the information to be sent to

the serverthe server» Can be formatted in various ways, with Can be formatted in various ways, with

different encodingsdifferent encodings» Ex: var=value pair query string (like what you Ex: var=value pair query string (like what you

see in the URL of a form submitted via GET)see in the URL of a form submitted via GET)– Sends the data to the server, where (maybe) a Sends the data to the server, where (maybe) a

script may run and the response is sent backscript may run and the response is sent back• readyStatereadyState

– Attribute that stores the current state of the Attribute that stores the current state of the objectobject

– Changes throughout the execution:Changes throughout the execution:» 0 0 uninitialized uninitialized» 1 1 loading loading» 2 2 loaded loaded» 3 3 interactive interactive» 4 4 complete complete

Page 47: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

47

Lecture 3: AJAXLecture 3: AJAX

• statusstatus– Did everything work correctly?Did everything work correctly?

» 200 – yes it did200 – yes it did» 404 – Not found404 – Not found» 500 – internal server error500 – internal server error» For more codes, seeFor more codes, seehttp://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

• responseTyperesponseType– What type of data did the server send back What type of data did the server send back

to the client?to the client?• response, responseText, responseXMLresponse, responseText, responseXML

– Get the data that was returnedGet the data that was returned– We can parse this to utilize the data to We can parse this to utilize the data to

update our pageupdate our page

Page 48: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

48

Lecture 3: AJAXLecture 3: AJAX

4 Big Picture:Big Picture:• The XMLHttpRequest object enables us The XMLHttpRequest object enables us

to interact with the server "behind the to interact with the server "behind the scenes" and update our web page scenes" and update our web page accordinglyaccordingly

• Server can still execute scripts as Server can still execute scripts as before (ex: PHP), but now it will send before (ex: PHP), but now it will send updates to the updates to the CURRENTCURRENT page rather page rather than an entirely new pagethan an entirely new page

4 Let's look at a simple exampleLet's look at a simple example• MozDemo.html – from Mozilla devel. siteMozDemo.html – from Mozilla devel. site

– Just demonstrates the basics of AJAXJust demonstrates the basics of AJAX

Page 49: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

49

Lecture 3: AJAXLecture 3: AJAX

4 Ok, that example was very simpleOk, that example was very simple

4 In a real situation, the response from In a real situation, the response from the server will require us to update our the server will require us to update our local page, possibly in a significant waylocal page, possibly in a significant way• How to do this? document.writeln()?How to do this? document.writeln()?

– Only works during initial rendering of the Only works during initial rendering of the pagepage

• Using DOM? Yes!Using DOM? Yes!– First we will look simply at HTMLFirst we will look simply at HTML

» Later we will look at XML and JSONLater we will look at XML and JSON– See: See: http://www.w3schools.com/htmldom/default.asp

• Idea: If we treat our local Web page as Idea: If we treat our local Web page as an object, then we can modify in an object, then we can modify in response to data sent back by the serverresponse to data sent back by the server

Page 50: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

50

Lecture 3: AJAX and DOMLecture 3: AJAX and DOM

4 For example, consider the methods For example, consider the methods /attributes for accessing/modifying data /attributes for accessing/modifying data in an HTML table:in an HTML table:• First we need to get the table itselfFirst we need to get the table itself

– If we assign it an "id" attribute, we can use the If we assign it an "id" attribute, we can use the method method getElementById()getElementById()

• We may then want a particular rowWe may then want a particular row– We can use the We can use the rows[]rows[] array array

• We may then want a specific cellWe may then want a specific cell– We can use the We can use the cells[]cells[] array from the row array from the row

• And we may want to modify that cellAnd we may want to modify that cell– We can use the We can use the innerHTMLinnerHTML attribute attribute

» Not true DOM – see code example for another Not true DOM – see code example for another wayway

Page 51: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

51

Lecture 3: AJAX and DOMLecture 3: AJAX and DOM

4 However, what if we want to make However, what if we want to make more significant changes?more significant changes?

4 Ex: Add a new row to a tableEx: Add a new row to a table• Get the table againGet the table again

• Insert a new row: Use Insert a new row: Use insertRow()insertRow()

• Insert a new cell: Use Insert a new cell: Use insertCell()insertCell()

• Add the data to the cellAdd the data to the cell– Use Use createTextNode()createTextNode() for text for text

» More complex for the radio button – see More complex for the radio button – see exampleexample

– Use Use appendChild()appendChild()

4 See CDpoll.php and tabulate.phpSee CDpoll.php and tabulate.php

Page 52: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 4: AJAX and DOMLecture 4: AJAX and DOM

• Caution:Caution:4 Be aware that AJAX can Be aware that AJAX can update data update data

locally locally and can cause inconsistency and can cause inconsistency with data at serverwith data at server

4 For example, consider 2 clients both For example, consider 2 clients both running CDpoll.phprunning CDpoll.php• Client 1 then adds a new write-in choiceClient 1 then adds a new write-in choice

• Client 2 also adds a new write-in choiceClient 2 also adds a new write-in choice– Both of these update the server DB, so any Both of these update the server DB, so any

new client new client will show themwill show them– However, Client 1 will not show Client 2However, Client 1 will not show Client 2’’s s

new choice and vice-versanew choice and vice-versa

52

Page 53: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 4: AJAX and DOMLecture 4: AJAX and DOM

4 So we need to either So we need to either • Get updates from as well as make Get updates from as well as make

updates to the server with each updates to the server with each connectionconnection

– But this may require a lot of work at each But this may require a lot of work at each connectionconnection

– See CDpoll2.php and tabulate2.phpSee CDpoll2.php and tabulate2.php

• Design our program in such a way that Design our program in such a way that we we ““syncsync”” with the server occasionally with the server occasionally

– Updates happen without any user Updates happen without any user interactioninteraction

53

Page 54: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 4: Updating the PageLecture 4: Updating the Page

4 One way to keep a page updated is to One way to keep a page updated is to have it automatically connect to a have it automatically connect to a server for new informationserver for new information

4 We can do this with our CD poll so that We can do this with our CD poll so that even if the user does not enter a new even if the user does not enter a new CD, we will still see entries that other CD, we will still see entries that other users have enteredusers have entered

4 This can be done in a fairly simple way This can be done in a fairly simple way utilizing:utilizing:• AJAX requestsAJAX requests

• A Javascript timerA Javascript timer

54

Page 55: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 4: Updating the PageLecture 4: Updating the Page

4 When the page is loaded the timer When the page is loaded the timer startsstarts

4 When it “goes off” an AJAX request is When it “goes off” an AJAX request is triggered to check with the server for triggered to check with the server for any new CD entriesany new CD entries• The timer is then reset for the next The timer is then reset for the next

requestrequest

4 See CDpoll-update.php andSee CDpoll-update.php andtabulate-update.phptabulate-update.php• Note that we now have some Note that we now have some

consistency concerns to considerconsistency concerns to consider

55

Page 56: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 4: Updating the PageLecture 4: Updating the Page

• Consider the following scenario:Consider the following scenario:– Timer goes off to update the pageTimer goes off to update the page– Before the result is posted to the table, the Before the result is posted to the table, the

user enters a new CD into the poll user enters a new CD into the poll (generating another request)(generating another request)

• In this situation, both requests will send In this situation, both requests will send back new rows for the table, and the back new rows for the table, and the HTML table will be updated twiceHTML table will be updated twice

• Note that the DB will still be consistentNote that the DB will still be consistent– What is not consistent is the clientWhat is not consistent is the client

• We can prevent this with some simple We can prevent this with some simple synchronizationsynchronization

– See CDpoll-update.phpSee CDpoll-update.php

56

Page 57: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Lecture 4: What about the Lecture 4: What about the ““XX ””??

• So far our AJAX examples have used a So far our AJAX examples have used a custom format to represent datacustom format to represent data4 And a custom parser to go along with itAnd a custom parser to go along with it

• Having a standard formatHaving a standard format4 Allows the use of standardized parsersAllows the use of standardized parsers

4 Improves the interoperability of programsImproves the interoperability of programs

• The two widely used AJAX formats:The two widely used AJAX formats:4 XMLXML (Extensible Markup Language) (Extensible Markup Language)

4 JSONJSON (JavaScript Object Notation) (JavaScript Object Notation)

57

Page 58: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

What about the X?What about the X?

• The The ““XX ”” in AJAX is for XML in AJAX is for XML

4 XML (Extensible Markup Language) is a XML (Extensible Markup Language) is a language for transfer and storage of language for transfer and storage of datadata• Syntax is similar to HTML (tree of tags)Syntax is similar to HTML (tree of tags)

• Tags describe Tags describe meaningmeaning rather than layout rather than layout

4 The result of a send() can be obtainedThe result of a send() can be obtained• As text using responseText attributeAs text using responseText attribute

• As XML using responseXML attributeAs XML using responseXML attribute

4 If we use responseXML we assume that If we use responseXML we assume that the server has sent an XML documentthe server has sent an XML document

58

Page 59: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

The XThe X

4 Once we have the XML document, we Once we have the XML document, we can parse, manipulate, update, etc. can parse, manipulate, update, etc. using DOMusing DOM4 DOM for XML is similar to DOM for HTMLDOM for XML is similar to DOM for HTML

4 One function that is used a lot with XML is One function that is used a lot with XML is getElementsByTagName()getElementsByTagName()

4 Allows access to any tagsAllows access to any tags

4 SeeSee• http://www.w3schools.com/xml/xml_dom.asp

• http://www.w3schools.com/xml/xml_server.asp

• Many others as well if you search the WebMany others as well if you search the Web

59

Page 60: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

The XThe X

• Idea:Idea:4 First we get the documentFirst we get the document

• var xmldoc = var xmldoc = httpReqObject.responseXML.documentElementhttpReqObject.responseXML.documentElement

• Then we can access it via tagsThen we can access it via tagsvar aTag = var aTag =

xmldoc.getElementsByTagName(xmldoc.getElementsByTagName(““tagnametagname””)[0].childNodes[0].nodeValue)[0].childNodes[0].nodeValue

– Whew!Whew!– What is this craziness?What is this craziness?– Basically it gets the data in the tag indicatedBasically it gets the data in the tag indicated– Complexity allows for nested tags (remember that Complexity allows for nested tags (remember that

the document is a tree)the document is a tree)» Note: Will be a lot easier with JQuery! Something to Note: Will be a lot easier with JQuery! Something to

look forward to!look forward to!

60

Page 61: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

The XThe X

4 Once we have the XML document we Once we have the XML document we can manipulate it in much the same can manipulate it in much the same way as the html documentway as the html document• See: See:

http://www.w3schools.com/dom/default.asp

4 See showBook.php and getBook.phpSee showBook.php and getBook.php

61

Page 62: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

The XThe X

• Let’s look at a (yet yet) another CD Let’s look at a (yet yet) another CD poll versionpoll version

4 This time we will change a few things:This time we will change a few things:

1)1)Unify PHP processing into one fileUnify PHP processing into one file• Think about previous versionsThink about previous versions

– PHP creates HTML table initially on the server PHP creates HTML table initially on the server sideside

– The table is later updated using AJAX, using The table is later updated using AJAX, using another PHP script to generate and send the another PHP script to generate and send the datadata

– Can we use AJAX to “update” the table initially?Can we use AJAX to “update” the table initially?» Yes!Yes!

– This makes the page more streamlined / This makes the page more streamlined / readable / consistentreadable / consistent

– See CDpoll-sortxml.phpSee CDpoll-sortxml.php

62

Page 63: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

The XThe X

2)2) Keep the data sortedKeep the data sorted• Up until now the CDs were in the order Up until now the CDs were in the order

submittedsubmitted

• No reason to keep them that wayNo reason to keep them that way

• Storing in some type of order (ex: Storing in some type of order (ex: alphabetical) makes sensealphabetical) makes sense

• This could be done in several ways, but This could be done in several ways, but the easiest is to sort them outside of the easiest is to sort them outside of HTML, in some raw formHTML, in some raw form

– This leads to point 3)This leads to point 3)

63

Page 64: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

The XThe X

3)3) Store the CDs locally on the clientStore the CDs locally on the client• Up until now we parsed the data and Up until now we parsed the data and

put it into an HTML tableput it into an HTML table

• Storing the CDs as raw data (ex: in an Storing the CDs as raw data (ex: in an array) will allow for more flexibilityarray) will allow for more flexibility

– For example it makes them easy to sortFor example it makes them easy to sort– In CDpoll-sortxml they are sorted In CDpoll-sortxml they are sorted

alphabetically, but it would be very easy to alphabetically, but it would be very easy to allow sorting on other fieldsallow sorting on other fields

– It will also help you with Assignment 3It will also help you with Assignment 3

64

Page 65: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

The XThe X

4)4) Keep the id and index of the CDs Keep the id and index of the CDs separateseparate• Up until now the id retrieved from the Up until now the id retrieved from the

DB corresponded to the row of the tableDB corresponded to the row of the table

• But now the table row depends on the But now the table row depends on the sort order, while the DB id depends on sort order, while the DB id depends on the insertion orderthe insertion order

4 See CDpoll-sortxml.phpSee CDpoll-sortxml.php

65

Page 66: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

JSONJSON

• XML is a very versatile formatXML is a very versatile format4 Versatility allows representation of all Versatility allows representation of all

kinds of semi-structured data / documentskinds of semi-structured data / documents

4 For structured data generated by For structured data generated by programming languages, it is a bit programming languages, it is a bit unwieldyunwieldy• Tree must be traversed to access nodesTree must be traversed to access nodes

• To be general, syntax requires extra codingTo be general, syntax requires extra coding– Ex: item.childNodes[0].nodeValueEx: item.childNodes[0].nodeValue

4 Maybe data can be sent in a simpler Maybe data can be sent in a simpler format?format?

66

Page 67: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

JSONJSON

• JSONJSON4 JJavaavaSScript cript OObject bject NNotationotation

• Data interchange format that allows Data interchange format that allows text to be converted into simple text to be converted into simple Javascript objects (and back)Javascript objects (and back)

4 We can use this to send data from a We can use this to send data from a server to an AJAX clientserver to an AJAX client• The client then generates Javascript The client then generates Javascript

primitive objects by processing the text primitive objects by processing the text datadata

67

Page 68: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

JSONJSON

4 Idea:Idea:• Data is really a set of key / value pairsData is really a set of key / value pairs

• Ex:Ex:CD.idCD.idCD.titleCD.titleCD.artistCD.artistCD.votesCD.votes

• JS Objects are also key / value pairsJS Objects are also key / value pairs

• Why not represent data as JS object Why not represent data as JS object literals?literals?

–For example, for CD data:For example, for CD data:{id: "1", title: "Parachutes", artist: "Coldplay", {id: "1", title: "Parachutes", artist: "Coldplay", votes: "2"}votes: "2"}

68

Page 69: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

JSONJSON

4 JSON formats data into object literals JSON formats data into object literals that can be directly converted to JS that can be directly converted to JS objectsobjects

4 On the PHP SERVER we can:On the PHP SERVER we can:• Put the data into a keyed PHP array:Put the data into a keyed PHP array:

– Remember when we said JavaScript objects Remember when we said JavaScript objects are really like keyed PHP arrays? Wink wink.are really like keyed PHP arrays? Wink wink.

– $A[‘id’] = 1;$A[‘id’] = 1;– $A[‘title’] = ‘Parachutes’;$A[‘title’] = ‘Parachutes’;……

• We can then call the function:We can then call the function:– json_encode()json_encode() to convert into JSON format to convert into JSON format– This translates the data into a JavaScript This translates the data into a JavaScript

object literal that can be sent to the clientobject literal that can be sent to the client69

Page 70: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

JSONJSON

4 On the CLIENT we canOn the CLIENT we can• Use the JSON.parse() function that Use the JSON.parse() function that

converts the JSON text into a simple converts the JSON text into a simple Javascript objectJavascript object

– The JS eval(string) function directly executes The JS eval(string) function directly executes the JSON text creating the object literal the JSON text creating the object literal which is tempting to usewhich is tempting to use

– But don’t use it! (Can be target for code But don’t use it! (Can be target for code injection)injection)

4 See:See:• http://en.wikipedia.org/wiki/JSON

• http://www.json.org/js.html

• CDpoll-sortjson.php, tabulate-json.phpCDpoll-sortjson.php, tabulate-json.php

70

Page 71: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

JSON with JQueryJSON with JQuery

4 As with XML, JQuery guesses on the As with XML, JQuery guesses on the return type and parses appropriatelyreturn type and parses appropriately• Note that this is not really a guessNote that this is not really a guess

• Rather, it is a deduction based on the Rather, it is a deduction based on the return headerreturn header

• See CDpoll-jqjson.phpSee CDpoll-jqjson.php

4 Let’s look at a FINAL (yes, it is true!) Let’s look at a FINAL (yes, it is true!) version of the CD pollversion of the CD poll• This one also allows sorting by This one also allows sorting by

individual columnsindividual columns

• See CDpoll-final.phpSee CDpoll-final.php

71

Page 72: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

XSLTXSLT

• We discussed using XSL style sheets We discussed using XSL style sheets to format XML documentsto format XML documents4 Sometimes we may want to extract Sometimes we may want to extract

parts of an XML document and format parts of an XML document and format them for inclusion into some other them for inclusion into some other document (ex: html) “on the fly”document (ex: html) “on the fly”• For example, we submit an AJAX request For example, we submit an AJAX request

and receive an XML document in and receive an XML document in responseresponse

• We use content from the XML document We use content from the XML document to update the current pageto update the current page

– One way of doing this (as seen in previous One way of doing this (as seen in previous examples) is via DOM / Javascriptexamples) is via DOM / Javascript

72

Page 73: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

XSLTXSLT

• We can also use We can also use XSLT XSLT to process the fileto process the file– We need to read in the .xsl file and use it to We need to read in the .xsl file and use it to

generate an generate an XSLTProcessorXSLTProcessor object object– We then pass our returned XML file to the We then pass our returned XML file to the

processor and use the result to update our processor and use the result to update our pagepage

– In some situations this can be much simpler / In some situations this can be much simpler / clearer than just using DOMclearer than just using DOM

– See: showRSS-xsl.php and formatRSS.xslSee: showRSS-xsl.php and formatRSS.xsl(Compare with showRSS.php)(Compare with showRSS.php)

– Note: THIS IS REALLY COOL!Note: THIS IS REALLY COOL!

• Also see some references:Also see some references:– http://en.wikipedia.org/wiki/XSLT– http://www.w3.org/TR/xslt – http://www.w3schools.com/xsl/– http://www.w3.org/TR/xpath/ – http://www.w3schools.com/xpath/default.asp

73

Page 74: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

APIsAPIs

• The Web is FULL of data!The Web is FULL of data!

4 Many many many sites have data that is Many many many sites have data that is accessible in various waysaccessible in various ways

4 We can set up our sites to access this We can set up our sites to access this data in interesting / useful waysdata in interesting / useful ways• Ex: Google Maps allows location Ex: Google Maps allows location

information to be integrated into a Web information to be integrated into a Web sitesite

• Ex: Weather Channel allows weather Ex: Weather Channel allows weather information to be accessedinformation to be accessed

• Ex: BreweryDB allows access to beer and Ex: BreweryDB allows access to beer and brewery informationbrewery information

74

Page 75: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

APIsAPIs

• See: See: http://www.programmableweb.com/category/all/apishttp://www.programmableweb.com/category/all/apis

• Generally, accessing an API is Generally, accessing an API is straightforwardstraightforward4 Typically users must request access to Typically users must request access to

the API via a token or keythe API via a token or key

4 Individual requests send the key plus Individual requests send the key plus the request detailsthe request details

4 Responses are sent back in some Responses are sent back in some standard formatstandard format• Ex: XML, JSON, etcEx: XML, JSON, etc

75

Page 76: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

APIsAPIs

4 Note that we need to do this on the Note that we need to do this on the server side since AJAX requests are not server side since AJAX requests are not allowed cross domain requestsallowed cross domain requests

• Let’s look at a simple example we Let’s look at a simple example we have already seen:have already seen:4 ISBNDBISBNDB

• This is a site which allows users to look This is a site which allows users to look up information about booksup information about books

• Searches can be done via ISBN, Author, Searches can be done via ISBN, Author, TitleTitle

• See examplesSee examples76

Page 77: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

APIsAPIs

• Various API ExamplesVarious API Examples

4 Google MapsGoogle Maps• https://maps.googleapis.com/maps/api/https://maps.googleapis.com/maps/api/

directions/xml?directions/xml?origin=Pittsburgh,PA&destination=Chicago,ILorigin=Pittsburgh,PA&destination=Chicago,IL

4 Open Weather MapOpen Weather Map• http://api.openweathermap.org/data/2.5/http://api.openweathermap.org/data/2.5/

weather?q=Pittsburgh&mode=xmlweather?q=Pittsburgh&mode=xml

4 ISBN DBISBN DB• http://isbndb.com/api/books.xml?http://isbndb.com/api/books.xml?

access_key=DROM5N4A&index1=full&value1access_key=DROM5N4A&index1=full&value1=Isaac+Asimov=Isaac+Asimov

77

Page 78: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Client-Side StorageClient-Side Storage

• Consider persistent data on the Consider persistent data on the serverserver4 We can keep session data in (ex.) We can keep session data in (ex.) PHP PHP

session variablessession variables• Persistent for current usePersistent for current use

4 We can keep long-term data in files or in a We can keep long-term data in files or in a databasedatabase

4 We have discussed both of these at lengthWe have discussed both of these at length

• What about the What about the clientclient??4 So far the only persistent data we have on So far the only persistent data we have on

the client is the client is cookiescookies

78

Page 79: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Client-Side StorageClient-Side Storage

4 Initial purpose of cookies was to convey Initial purpose of cookies was to convey information information from the clientfrom the client to the serverto the server• So even though the data was stored on So even though the data was stored on

the client, cookies were not really used the client, cookies were not really used by the clientby the client

4 However, cookies are accessible to the However, cookies are accessible to the client so we can look at them and even client so we can look at them and even create them locally if we wishcreate them locally if we wish• With the increase in client-side scripting, With the increase in client-side scripting,

we may want to access / create / utilize we may want to access / create / utilize cookies to help make decisions in our cookies to help make decisions in our Javascript programsJavascript programs

79

Page 80: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Client-Side StorageClient-Side Storage

• We can also manipulate cookies’ values We can also manipulate cookies’ values that are utilized during AJAX requests to that are utilized during AJAX requests to the serverthe server

– See jq-cookie.htmlSee jq-cookie.html– Note that here we are using a JQuery plug-in Note that here we are using a JQuery plug-in

to allow for easy cookie manipulationto allow for easy cookie manipulation» These are GREAT but if you are using them These are GREAT but if you are using them

make sure you have the .js code accessiblemake sure you have the .js code accessible» There are MANY other JQuery plug-ins availableThere are MANY other JQuery plug-ins available» Google to see someGoogle to see some

• If we really wanted to, we could use If we really wanted to, we could use cookies exclusively client-side if we cookies exclusively client-side if we wantedwanted

– Maintain / update persistent data for use by Maintain / update persistent data for use by our scriptsour scripts

– See jqex4-cookie.htmlSee jqex4-cookie.html80

Page 81: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Client-Side StorageClient-Side Storage

4 However, cookies have some of the However, cookies have some of the same drawbacks when used on the same drawbacks when used on the client that they did on the serverclient that they did on the server• Limited size (4K)Limited size (4K)

• Kind of clunky to use / accessKind of clunky to use / access– To store lots of data we need lots of cookiesTo store lots of data we need lots of cookies– Must recall / extract each oneMust recall / extract each one

4 So, cookies are fine and useful, but it So, cookies are fine and useful, but it would be nice if we had another option would be nice if we had another option for client-side storagefor client-side storage

81

Page 82: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Client-Side StorageClient-Side Storage

• Is there an alternative?Is there an alternative?4 With HTML 5 – yes!With HTML 5 – yes!

4 We can now keep client-side data in a We can now keep client-side data in a fashion very similar to that of server-side fashion very similar to that of server-side datadata

4 We have two global variables that are We have two global variables that are incorporated into our browser window incorporated into our browser window and which can be accessed / updated and which can be accessed / updated from our scripts:from our scripts:• sessionStoragesessionStorage

– Keeps data for current browser session (while Keeps data for current browser session (while window or tab remains open)window or tab remains open)

82

Page 83: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Client-Side StorageClient-Side Storage

• localStoragelocalStorage– Keeps data indefinitelyKeeps data indefinitely

4 Both of these variables store data in Both of these variables store data in key / value pairskey / value pairs• Both the key and value must be strings, Both the key and value must be strings,

which could be a problem if we want to which could be a problem if we want to store more complex datastore more complex data

• Solution: Solution: – Use JSON.stringify() to convert from Use JSON.stringify() to convert from

Javascript objects to JSON in order to storeJavascript objects to JSON in order to store– Use JSON.parse() to convert back when Use JSON.parse() to convert back when

accessingaccessing– A bit of work but the best we can do right A bit of work but the best we can do right

nownow

83

Page 84: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Client-Side StorageClient-Side Storage

• The amount of storage available does The amount of storage available does not have a predefined limitnot have a predefined limit

– However, many browsers specify a limit per However, many browsers specify a limit per domain, or overalldomain, or overall

– Usually it is several Mb per domainUsually it is several Mb per domain

4 Syntax:Syntax:• Both localStorage and sessionStorage Both localStorage and sessionStorage

can be accessed as Javascript objectscan be accessed as Javascript objects

• Functions which are of interest to us:Functions which are of interest to us:– setItem(key, value)setItem(key, value)

» Puts the value at the specified keyPuts the value at the specified key» Key and value must both be a string, but they Key and value must both be a string, but they

could be JSON (stringified objects)could be JSON (stringified objects)

84

Page 85: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Client-Side StorageClient-Side Storage

– getItem(key)getItem(key)» Retrieve the value at the specified keyRetrieve the value at the specified key» If no value is there, it returns nullIf no value is there, it returns null

– removeItem(key)removeItem(key)» Remove the item at the given keyRemove the item at the given key» Will be set back to nullWill be set back to null

– lengthlength» Note that it is NOT a function – rather it is an Note that it is NOT a function – rather it is an

attribute valueattribute value» Returns the number of values stored in the Returns the number of values stored in the

storagestorage– key(index)key(index)

» Return the key at a given indexReturn the key at a given index» Index values of keys are maintained in some Index values of keys are maintained in some

sequential waysequential way» Thus, to get all keys in localStorage we can Thus, to get all keys in localStorage we can

iterate the the indexes from 0 to length iterate the the indexes from 0 to length

• For more info, see For more info, see

https://developer.mozilla.org/en/DOM/Storage https://developer.mozilla.org/en/DOM/Storage 85

Page 86: 1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez / Wonsun Ahn Department of Computer Science University of Pittsburgh

Client-Side StorageClient-Side Storage

4 Let’s look at another exampleLet’s look at another example• Same as jqex4.html but now each poll Same as jqex4.html but now each poll

we take will be saved into local storagewe take will be saved into local storage

• User can choose to see any previous User can choose to see any previous resultsresults

• See: jqex4-local.htmlSee: jqex4-local.html

86