Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez Department of Computer Science University of Pittsburgh."— Presentation transcript:

1

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

3 2 These notes are intended for use by students in CS1520 at the University of Pittsburgh and no one elseThese notes are intended for use by students in CS1520 at the University of Pittsburgh and no one else These notes are provided free of charge and may not be sold in any shape or formThese notes are provided free of charge and may not be sold in any shape or form Material from these notes is obtained from various sources, including, but not limited to, the following:Material from these notes is obtained from various sources, including, but not limited to, the following:  Programming the World Wide Web, multiple editions, by Robert Sebesta (AW)  JavaScript by Don Gossein (Thomson Learning)  https://developer.mozilla.org/en/JavaScript/Reference https://developer.mozilla.org/en/JavaScript/Reference  http://www.w3schools.com/jsref/default.asp http://www.w3schools.com/jsref/default.asp  http://www.w3.org/TR/XMLHttpRequest/ http://www.w3.org/TR/XMLHttpRequest/

4 3 Lecture 1: Intro to JavaScript What is JavaScript?What is JavaScript?  Language developed by Netscape  Primary purpose is for "client-end" processing of HTML documents JavaScript code is embedded within the html of a documentJavaScript code is embedded within the html of a document An interpreter in the browser interprets the JavaScript code when appropriateAn interpreter in the browser interprets the JavaScript code when appropriate Code typically allows for "preprocessing" of forms and can add "dynamic content" to a Web pageCode typically allows for "preprocessing" of forms and can add "dynamic content" to a Web page

5 4 Lecture 1: JavaScript Basics How to include JavaScript in html?How to include JavaScript in html?  JavaScript programs require the tag in.html files ACTUAL JavaScript code here </script>  These can appear in either the or section of an html document Functions and code that may execute multiple times is typically placed in the Functions and code that may execute multiple times is typically placed in the –These are only interpreted when the relevant function or event-handler are called

6 5 Lecture 1: JavaScript Basics Code that needs to be executed only once, when the document is first loaded is placed in the Code that needs to be executed only once, when the document is first loaded is placed in the  Some browsers may not support scripting (i.e. have it turned off) To be safe, you could put your scripts in html comments as specified in Sebesta textTo be safe, you could put your scripts in html comments as specified in Sebesta text –This way browsers that do not recognize JavaScript will look at the programs as comments  Note that, unlike PHP scripts, JavaScripts are visible in the client browser Since they are typically acting only on the client, this is not a problemSince they are typically acting only on the client, this is not a problem

7 6 Lecture 1: JavaScript Basics  However, if we want to prevent the script itself from being (easily) seen, we can upload our JavaScript from a file This will show only the upload tag in our final document, not the JavaScript from the fileThis will show only the upload tag in our final document, not the JavaScript from the file Use the src option in the tagUse the src option in the tag –However, the source is likely still not really hidden –In a temp folder somewhere on computer and can be seen with a utility like FireBug –Thus you should not "hardcode" into Javascript anything that you don't want the client to see

8 7 Lecture 1: Simple Example <HTML><HEAD> First JavaScript Example First JavaScript Example </HEAD><BODY> This line is straight HTML This line is straight HTML <H3> document.write("These lines are produced by "); document.write("These lines are produced by "); document.write("the JavaScript program "); document.write("the JavaScript program "); alert("Hey, JavaScript is fun!"); alert("Hey, JavaScript is fun!");</SCRIPT></H3> More straight HTML More straight HTML </BODY></HTML>

9 8 Lecture 1: JavaScript Variables  JavaScript variables have no types Type is determined dynamically, based on the value storedType is determined dynamically, based on the value stored –This is becoming familiar! –The typeof operator can be used to check type of a variable  Declarations are made using the var keyword Can be implicitly declared, but not advisableCan be implicitly declared, but not advisable Declarations outside of any function are globalDeclarations outside of any function are global Declarations within a function are local to that functionDeclarations within a function are local to that function Variables declared but not initialized have the value undefinedVariables declared but not initialized have the value undefined

10 9 Lecture 1: JavaScript Variables  Variable identifiers are similar to those in 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 digits Case sensitiveCase sensitive

11 10 Lecture 1: JavaScript Expressions  Numeric operators in JavaScript are similar to those in most languages +, –, *, /, %, ++, -- Precedence and associativity are also fairly standardPrecedence and associativity are also fairly standard  Strings Have the + operator for concatenationHave the + operator for concatenation Have a number of methods to do typical string operationsHave a number of methods to do typical string operations –charAt, indexOf, toLowerCase, substring Looks kind of like Java – intentionallyLooks kind of like Java – intentionally

12 11 Lecture 1: JavaScript Expressions  Similar to PHP, with mixed number/string type expressions, JavaScript will coerce if it can If operator is + and an operand is string, it will always coerce other to stringIf operator is + and an operand is string, it will always coerce other to string If operator is arithmetic, and string value can be coerced to a number it will do soIf operator is arithmetic, and string value can be coerced to a number it will do so –If string is non-numeric, result is NaN (NotaNumber) We can also explicitly convert the string to a number using parseInt and parseFloatWe can also explicitly convert the string to a number using parseInt and parseFloat –Again looks like Java  See ex2.html

13 12 Lecture 1: Control Statements Relational operators:Relational operators: ==, !=,, = The above allow for type coercion. To prevent coercion there is alsoThe above allow for type coercion. To prevent coercion there is also ===, !== –Similar to PHP Boolean operatorsBoolean operators &&, ||, ! &&, || are short-circuited (as in Java and PHP)&&, || are short-circuited (as in Java and PHP) –Discuss

14 13 Lecture 1: Control Statements Control statements similar to JavaControl statements similar to Java  if, while, do, for, switch Variables declared in for loop header are global to the rest of the scriptVariables declared in for loop header are global to the rest of the script FunctionsFunctions  Similar to Java functions, but Header is somewhat differentHeader is somewhat different function name(param_list) –Return type not specified (like PHP, since JS has dynamic typing) –Param types also not specified

15 14 Lecture 1: Functions Functions execute when they are called, just as in any languageFunctions execute when they are called, just as in any language To allow this, function code should be in the section of the.html fileTo allow this, function code should be in the section of the.html file Variables declared in a function are local to the functionVariables declared in a function are local to the function Parameters are all valueParameters are all value –No parameter type-checking –Numbers of formal and actual parameters do not have to correspond »Extra actual parameters are ignored »Extra formal parameters are undefined –All actual parameters can be accessed regardless of formal parameters by using the arguments array See ex3.htmlSee ex3.html

16 15 Lecture 1: Array Objects  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 arraysCannot use arbitrary keys as with PHP arrays  Creating arrays Using the new operator and a constructor with multiple argumentsUsing the new operator and a constructor with multiple arguments var A = new Array("hello", 2, "you"); Using the new operator and a constructor with a single numeric argumentUsing the new operator and a constructor with a single numeric argument var B = new Array(50); Using square brackets to make a literalUsing square brackets to make a literal var C = ["we", "can", 50, "mix", 3.5, "types"];

17 16 Lecture 1: Array Objects  Array Length Like in Java, length is an attribute of all array objectsLike in Java, length is an attribute of all array objects However, in Javascript it does not necessarily represent the number of items or even mem. locations in the arrayHowever, in Javascript it does not necessarily represent the number of items or even mem. locations in the array Unlike Java, length can be changed by the programmerUnlike Java, length can be changed by the programmer Actual memory allocation is dynamic and occurs when necessaryActual memory allocation is dynamic and occurs when necessary –An array with length = 1234 may in fact have memory allocated for only a few elements –When accessed, empty elements are undefined

18 17 Lecture 1: Array Objects Array Methods TTTThere are a number of predefined operations that you can do with arrays – c– c– c– concat two arrays into one – j– j– j– join array items into a single string (commas between) – p– p– p– push, pop, shift, unshift »P»P»P»Push and pop are a "right stack" »S»S»S»Shift and unshift are a "left stack" – s– s– s– sort »S»S»S»Sort by default compares using alphabetical order »T»T»T»To sort using numbers we pass in a comparison function defining how the numbers will be compared – r– r– r– reverse »R»R»R»Reverse the items in an array

19 18 Lecture 1: Array Objects These operations are invoked via method calls, in an object-based wayThese operations are invoked via method calls, in an object-based way –Also many, such as sort and reverse are mutators, affecting the array itself  JavaScript also has 2-dimensional arrays Created as arrays of arrays, but references are not neededCreated as arrays of arrays, but references are not needed  see ex4.html

20 19 Lecture 1: JavaScript Objects JavaScript is an object-based languageJavaScript is an object-based language  It is NOT object-oriented  It has and uses objects, but does not support some features necessary for object-oriented languages Class inheritance and polymorphism not supportedClass inheritance and polymorphism not supported –They can be “faked” but are not really there –http://www.webreference.com/js/column79/ http://www.webreference.com/js/column79/ –http://www.webreference.com/js/column80/ http://www.webreference.com/js/column80/

21 20 Lecture 1: JavaScript Objects  JavaScript objects are actually represented as property-value pairs Actually similar to keyed arrays in PHPActually similar to keyed arrays in PHP The object is analogous to the array, and the properties are analogous to the keysThe object is analogous to the array, and the properties are analogous to the keys –However, the property values can be data or functions (methods) Ex:Ex: 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;

22 21 Lecture 1: JavaScript Objects Note that the objects can be created and their properties can be changed dynamicallyNote that the objects can be created and their properties can be changed dynamically Also, objects all have the same data type – objectAlso, objects all have the same data type – object We can write constructor functions for objects if we'd like, but these do not create new data types – just easy ways of uniformly initializing objectsWe can write constructor functions for objects if we'd like, but these do not create new data types – just easy ways of uniformly initializing objects 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);

23 22 Lecture 1: JavaScript Objects Once an object is constructed, I can change its properties if I want toOnce an object is constructed, I can change its properties if I want to –Let’s say I want to add a method to my TV called "show_properties" function show_properties() { document.write("Here is your TV: "); document.write("Brand: ", this.brand," "); document.write("Size: ", this.size, " "); document.write("Input Jacks: "); document.write(this.jacks.input, " "); document.write("Output Jacks: "); document.write(this.jacks.output, " "); } … ; my_tv.show = show_properties; –See ex5.html

24 Lecture 1: Javascript Objects We can do a lot with Javascript objectsWe can do a lot with Javascript objects  Even though Javascript is not truly object- oriented, we can program in an object-based way Encapsulating data and methods within objectsEncapsulating data and methods within objects Utilizing methods for operations on the objectsUtilizing methods for operations on the objects See ex6.htmlSee ex6.html  We will be using Javascript objects a lot with client-side programming 23

25 24 Lecture 1: Regular Expressions  JavaScript regular expression handling is also based on that in Perl The patterns and matching procedures are the same as in Perl, Java and PHP (PCRE)The patterns and matching procedures are the same as in Perl, Java and PHP (PCRE) However, now the functions are methods within a string object (similar to Java)However, now the functions are methods within a string object (similar to Java) var s = "a man, a plan, a canal: panama"; var loc = s.search(/plan/); var matches1 = s.match(/an/g); var matches2 = s.match(/\w+/g); var matches3 = s.split(/\W+/); s = s.replace(/\W/g, "-"); –Note that match is similar to the PHP match function »Returns the matched pieces as opposed to the non- matched pieces (that split returns) See ex7.htmlSee ex7.html

26 25 Lecture 2: DOM The Document Object ModelThe Document Object Model  Developed by W3C (World-Wide Web Consortium) http://www.w3c.org/DOM/http://www.w3c.org/DOM/http://www.w3c.org/DOM/  Specifies the contents of Web documents in an object-oriented way Allows programming languages to access and manipulate the components of documentsAllows programming languages to access and manipulate the components of documents Defined at a high level so that a variety of languages can be used with itDefined at a high level so that a variety of languages can be used with it It is still being updated / revisedIt is still being updated / revised  We will not cover this completely – investigate!

27 Lecture 2: DOM History / IdeaHistory / Idea  HTML and XML documents consist of tags  Well-formatted documents (required in XHTML and XML) can be viewed as a tree Ex: http://www.w3schools.com/htmldom/default.aspEx: http://www.w3schools.com/htmldom/default.asp http://www.w3schools.com/htmldom/default.asp  DOM provides a language-independent, object-based model for accessing / modifying and adding to these tags  DOM 0 Not formally specified by W3C but includes a lot of useful functionalityNot formally specified by W3C but includes a lot of useful functionality 26

28 Lecture 2: DOM  DOM 1, 2, 3 Formal specifications of model and functionalityFormal specifications of model and functionality Each builds on / improves previousEach builds on / improves previous  DOM 4 is being finalized  With recent browsers there is general DOM compatibility IE through IE8 does not fully support DOM 2IE through IE8 does not fully support DOM 2 –It has its own syntax for event attachment So if client is using older IE some newer DOM features may not workSo if client is using older IE some newer DOM features may not work 27

29 28 Lecture 2: Events  With documents DOM specifies events and event handlers Event model is similar to the one used in JavaEvent model is similar to the one used in Java Different parts of a document have different events associated with themDifferent parts of a document have different events associated with them We can define handlers to react to these eventsWe can define handlers to react to these events  These allow us to "interact" with and add "dynamic content" to web documents Ex: Can preprocess form elementsEx: Can preprocess form elements Ex: Can load / update / change what is displayed in response to an eventEx: Can load / update / change what is displayed in response to an event

30 29 Lecture 2: DOM and Events document refers to the top-level documentdocument refers to the top-level document  Each document has access to its properties and to the components that are declared within it Ex: title, URL, forms[], images[]Ex: title, URL, forms[], images[] Attributes with IDs can also be specified by ID (from DOM 1)Attributes with IDs can also be specified by ID (from DOM 1)  Once we know the components, events and event- handlers, we can write JavaScript programs to process Web pages on the client-side Client computers are typically less busy than servers, so whatever we can do at the client will be helpful overallClient computers are typically less busy than servers, so whatever we can do at the client will be helpful overall

31 30 Lecture 2: DOM and Events –Ex: Checking form correctness before it is submitted  In HTML documents events are specified through tag attributes Within the tag identifying an HTML component, we can specify in an attribute how the component reacts to various eventsWithin the tag identifying an HTML component, we can specify in an attribute how the component reacts to various events  See Sebesta Table 5.1 for events and tag attributes and Table 5.2 for the tags that have a given attribute  Similar in idea to Java, we assign event handling code to the tag attributes, and the code executes when the event occurs

32 Lecture 2: Events We can also attach events in JavascriptWe can also attach events in Javascript  In DOM 0, events are attached in an “inline” way: Ex: theElement.onclick = functionNameEx: theElement.onclick = functionName  In DOM 2, a more flexible event model was developed, so that more than one handler could be attached to the same event: Ex: theElement.addEventListener(type, fn, opt)Ex: theElement.addEventListener(type, fn, opt) –Where opt is a boolean to determine if the event is “captured” or “bubbles” »See: http://en.wikipedia.org/wiki/DOM_Events http://en.wikipedia.org/wiki/DOM_Events Unfortunately, IE (up through IE8) does not use DOM 2Unfortunately, IE (up through IE8) does not use DOM 2 –It has its own, similar model 31

33 32 Lecture 2: DOM and Events  Ex: Event mouseover occurs when the mouse is place over a displayed element Elements that allow for the mouseover event have the attribute onmouseoverElements that allow for the mouseover event have the attribute onmouseover In HTML or Javascript, the programmer assigns a function call to the attribute, so that when the event occurs the function is calledIn HTML or Javascript, the programmer assigns a function call to the attribute, so that when the event occurs the function is called We can define showChoice however we'd likeWe can define showChoice however we'd like –ex: alert("You are about to choose Choice 1");

34 33 Lecture 2: Example: Pre-processing a Form A very common client-side operation is pre-processing a formA very common client-side operation is pre-processing a form  Ensure that fields are filled and formatted correctly, so server does not have to Saves load on the server, saves time and saves bandwidthSaves load on the server, saves time and saves bandwidth We can check a form overall by using the attribute onsubmitWe can check a form overall by using the attribute onsubmit –We can put it right into the form as an attribute –Or we can assign the attribute through the document object in Javascript

35 34 Lecture 2: Example: Pre-processing a form We can check individual components as they are entered as wellWe can check individual components as they are entered as well –Ex: has the onchange attribute » Triggered when contents are changed and focus changes –Ex: has the onclick attribute »Triggered when the radio button is clicked with the mouse See ex8.htmlSee ex8.html –Note: Script to process this form is not shown –You may want to write it as an exercise –Also note Firebug or Web Inspector – use it if you can!

36 35 Lecture 2: Processing Multiple Forms and Multiple Submits  Web pages can also have multiple forms These can be handled both on the client side using JavaScript and on the server sideThese can be handled both on the client side using JavaScript and on the server side Idea is to identify which form has been submitted and respond accordinglyIdea is to identify which form has been submitted and respond accordingly –See mform.html and mform.php  Similarly, we can have multiple submits of a single form See also msub.html and msub.phpSee also msub.html and msub.php  One more example demonstrating DOM See ex9.htmlSee ex9.html

37 36 Lecture 3: AJAX Asynchronous JavaScript And XMLAsynchronous JavaScript And XML This is technique that was coined in Feb. 2005 but that has been used (more or less) for quite a while before thatThis is technique that was coined in Feb. 2005 but that has been used (more or less) for quite a while before that It allows the client and the server to communicate without requiring a "hard" submit and page refreshIt allows the client and the server to communicate without requiring a "hard" submit and page refresh –In particular, the page can be updated without reloading it in its entirety Makes the user interface for a Web app. appear more like that of a desktop appMakes the user interface for a Web app. appear more like that of a desktop app See: http://en.wikipedia.org/wiki/AJAXSee: http://en.wikipedia.org/wiki/AJAX http://en.wikipedia.org/wiki/AJAX http://developer.mozilla.org/en/docs/AJAX

38 37 Lecture 3: AJAX  Let's look at a few details and some simple examples You may also want to research it on your ownYou may also want to research it on your own  AJAX centers around the XMLHttpRequest object  This object allows the client to connect to a server and to respond to the reply once it has become available  There is a lot that can be done with this, especially in conjunction with XML and JSON – we will mention these later

39 38 Lecture 3: AJAX  It is a bit tricky to use, and is not consistent across all browsers (esp. older versions)  However, once you get the hang of it, it can be a very useful tool and it is REALLY COOL!  Basic Idea: Programmer creates an instance of an XMLHttpRequest objectProgrammer creates an instance of an XMLHttpRequest object Several useful attributes and methods are associated with this object:Several useful attributes and methods are associated with this object: –see: http://www.w3.org/TR/XMLHttpRequest/ http://www.w3.org/TR/XMLHttpRequest/ –Let's look at a few of them to see how they work together

40 39 Lecture 3: AJAX onreadystatechangeonreadystatechange –Attribute to which we assign an EventListener (which is a function callback) –This will associate the function with the occurrence of the readystatechange event »This event fires in several places, throughout the the execution (each time the state changes) »We can check the readyState to see what, if anything, we will do in response – more on this soon open(method, url, async)open(method, url, async) »Where "method" is an HTTP method »Where "url" is the location of the server »Where "async" is a boolean to determine if the transfer is to be done asynchronously or not –Method to switch the object to the open state – i.e. get ready to send data to the server

41 40 Lecture 3: AJAX send(data)send(data) »Where "data" is a the information to be sent to the server »Can be formatted in various ways, with different encodings »Ex: var=value pair query string (like what you see in the URL of a form submitted via GET) –Sends the data to the server, where (maybe) a script may run and the response is sent back readyStatereadyState –Attribute that stores the current state of the object –Changes throughout the execution: »0  uninitialized »1  loading »2  loaded »3  interactive »4  complete

42 41 Lecture 3: AJAX statusstatus –Did everything work correctly? »200 – yes it did »404 – Not found »500 – internal server error »For more codes, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html responseTyperesponseType –What type of data did the server send back to the client? response, responseText, responseXMLresponse, responseText, responseXML –Get the data that was returned –We can parse this to utilize the data to update our page

43 42 Lecture 3: AJAX  Big Picture: The XMLHttpRequest object enables us to interact with the server "behind the scenes" and update our web page accordinglyThe XMLHttpRequest object enables us to interact with the server "behind the scenes" and update our web page accordingly Server can still execute scripts as before (ex: PHP), but now it will send updates to the CURRENT page rather than an entirely new pageServer can still execute scripts as before (ex: PHP), but now it will send updates to the CURRENT page rather than an entirely new page Show on boardShow on board  Let's look at a simple example MozDemo.html – from Mozilla devel. siteMozDemo.html – from Mozilla devel. site –Just demonstrates the basics of AJAX

44 43 Lecture 3: AJAX  Ok, that example was very simple  In a real situation, the response from the server will require us to update our local 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 page Using DOM? Yes!Using DOM? Yes! –First we will look simply at HTML »Later we will look at XML and JSON –See: http://www.w3schools.com/js/js_htmldom.asp http://www.w3schools.com/js/js_htmldom.asp –Idea: If we treat our local Web page as an object, then we can modify in response to data sent back by the server

45 44 Lecture 3: AJAX and DOM  For example, consider the methods /attributes for accessing/modifying data 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 method getElementById() We may then want a particular rowWe may then want a particular row –We can use the rows[] array We may then want a specific cellWe may then want a specific cell –We can use the cells[] array from the row And we may want to modify that cellAnd we may want to modify that cell –We can use the innerHTML attribute »Not true DOM – see handout for another way See CDpoll.php and tabulate.phpSee CDpoll.php and tabulate.php

46 45 Lecture 3: AJAX and DOM  However, what if we want to make more significant changes?  Ex: Add a new row to a table Get the table againGet the table again Insert a new rowInsert a new row –Use insertRow() Insert a new cellInsert a new cell –Use insertCell() Add the data to the cellAdd the data to the cell –Use createTextNode() for text »More complex for the radio button – see handout –Use appendChild()

47 Lecture 3: AJAX and DOM Caution:Caution:  Be aware that AJAX can update data locally and can cause inconsistency with data at server  For example, consider 2 clients both running 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 new client will show them –However, Client 1 will not show Client 2’s new choice and vice-versa 46

48 Lecture 3: AJAX and DOM  So we need to either Get updates from as well as make updates to the server with each connectionGet updates from as well as make updates to the server with each connection –But this may require a lot of work at each connection –See CDpoll2.php and tabulate2.php Design our program in such a way that we only need to “sync” with the server occasionallyDesign our program in such a way that we only need to “sync” with the server occasionally –Updates from one client do not affect another Use the server to read from but not to write toUse the server to read from but not to write to –Consistency is not a problem if data does not change 47

49 Lecture 3: Updating the Page  One way to keep a page updated is to have it automatically connect to a server for new information  We can do this with our CD poll so that even if the user does not enter a new CD, we will still see entries that other users have entered  This can be done in a fairly simple way utilizing: AJAX requestsAJAX requests A Javascript timerA Javascript timer 48

50 Lecture 3: Updating the Page  When the page is loaded the timer starts  When it “goes off” an AJAX request is triggered to check with the server for any new CD entries The timer is then reset for the next requestThe timer is then reset for the next request  See CDpoll-update.php and tabulate-update.php Note that we now have some consistency concerns to considerNote that we now have some consistency concerns to consider 49

51 Lecture 3: Updating the Page Consider the following scenario:Consider the following scenario: –Timer goes off to update the page –Before the result is posted to the table, the user enters a new CD into the poll (generating another request) In this situation, both requests will send back new rows for the table, and the table will be updated twiceIn this situation, both requests will send back new rows for the table, and the 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 client We can prevent this with some simple synchronizationWe can prevent this with some simple synchronization –See CDpoll-update.php 50

52 Lecture 3: What about the “X”? So far our AJAX examples have used responseTextSo far our AJAX examples have used responseText Where does the XML come in?Where does the XML come in? AJAX these days also utilizes JSON objects as a responseAJAX these days also utilizes JSON objects as a response  What are these and how are they used? We will talk about XML now and JSON a bit later onWe will talk about XML now and JSON a bit later on 51

53 What about the X? The “X” in AJAX is for XMLThe “X” in AJAX is for XML  The result of a send() to a server can be obtained As text using responseText attributeAs text using responseText attribute As XML using responseXML attributeAs XML using responseXML attribute  If we use responseXML we assume that the server has sent a well-formed XML file back to us Not necessarily valid – see XML notes for differenceNot necessarily valid – see XML notes for difference 52

54 The X  Once we have the XML document, we can parse, manipulate, update, etc. using DOM  DOM for XML is similar to DOM for HTML  One function that is used a lot with XML is getElementsByTagName()  Allows access to any tags, regardless of that they are  See http://www.w3schools.com/xml/xml_dom.asphttp://www.w3schools.com/xml/xml_dom.asphttp://www.w3schools.com/xml/xml_dom.asp http://www.w3schools.com/xml/xml_server.asphttp://www.w3schools.com/xml/xml_server.asphttp://www.w3schools.com/xml/xml_server.asp Many others as well if you search the WebMany others as well if you search the Web  Let’s look at a couple examples 53

55 The X Idea:Idea:  First we get the document var xmldoc = httpReqObject.responseXML.documentElementvar xmldoc = httpReqObject.responseXML.documentElement Then we can access it via tagsThen we can access it via tags var aTag = xmldoc.getElementsByTagName(“tagname”)[0].childNodes[0].nodeValue –Whew! –What is this craziness? –Basically it gets the data in the tag indicated –Complexity allows for nested tags (remember that the document is a tree) »Note: Will be a lot easier with JQuery! Something to look forward to! 54

56 The X  Once we have the XML document we can manipulate it in much the same way as the html document See: http://www.w3schools.com/dom/default.aspSee: http://www.w3schools.com/dom/default.asp http://www.w3schools.com/dom/default.asp  Let's look at some very simple examples Simple Joke display programSimple Joke display program EXTREMELY primitive RSS readerEXTREMELY primitive RSS reader ISBN book lookupISBN book lookup CD poll (yet ANOTHER version!!)CD poll (yet ANOTHER version!!) 55

57 The X Let’s look at a (yet yet) another CD poll versionLet’s look at a (yet yet) another CD poll version  This time we will change a few things: 1)Get rid of PHP entirely Think about previous versionsThink about previous versions –PHP creates table initially on the server side –The table is updated in various ways using AJAX, using another PHP script to generate and send the data –Couldn’t we use AJAX to “update” the entire table? »Yes! –This makes the page more streamlined / readable / consistent –See CDpoll-sortxml.php 56

58 The X 2)Keep the data sorted Up until now the CDs were in the order submittedUp until now the CDs were in the order submitted No reason to keep them that wayNo reason to keep them that way Storing in some type of order (ex: alphabetical) makes senseStoring in some type of order (ex: alphabetical) makes sense This could be done in several ways, but the easiest is to sort them outside of HTML, in some raw formThis could be done in several ways, but the easiest is to sort them outside of HTML, in some raw form –This leads to point 3) 57

59 The X 3)Store the CDs locally on the client Up until now we parsed the data and put it into an HTML tableUp until now we parsed the data and put it into an HTML table Storing the CDs as raw data (ex: in an array) will allow for more flexibilityStoring the CDs as raw data (ex: in an array) will allow for more flexibility –For example it makes them easy to sort –In CDpoll-sortxml they are sorted alphabetically, but it would be very easy to allow sorting on other fields 58

60 The X 4)Keep the id and index of the CDs separate Up until now the id retrieved from the DB corresponded to the row of the tableUp until now the id retrieved from the DB corresponded to the row of the table But now the table row depends on the sort order, while the DB id depends on the insertion orderBut now the table row depends on the sort order, while the DB id depends on the insertion order –Thus we must keep these values separate and manage both of them –This is probably a better way to store the data anyway  See CDpoll-sortxml.php 59

61 XSLT We discussed using XSL style sheets to format XML documentsWe discussed using XSL style sheets to format XML documents  Sometimes we may want to extract parts of an XML document and format them for inclusion into some other document (ex: html) “on the fly” For example, we submit an AJAX request and receive an XML document in responseFor example, we submit an AJAX request and receive an XML document in response We use content from the XML document to update the current pageWe use content from the XML document to update the current page –One way of doing this (as seen in previous examples) is via DOM / Javascript 60

62 XSLT We can also use XSLT to process the fileWe can also use XSLT to process the file –We need to read in the.xsl file and use it to generate an XSLTProcessor object –We then pass our returned XML file to the processor and use the result to update our page –In some situations this can be much simpler / clearer than just using DOM –See: showRSS-xsl.php and formatRSS.xsl –Note: THIS IS REALLY COOL! Also see some references:Also see some references: –http://en.wikipedia.org/wiki/XSLT http://en.wikipedia.org/wiki/XSLT –http://www.w3.org/TR/xslt http://www.w3.org/TR/xslt –http://www.w3schools.com/xsl/ http://www.w3schools.com/xsl/ –http://www.w3.org/TR/xpath/ http://www.w3.org/TR/xpath/ –http://www.w3schools.com/xpath/default.asp http://www.w3schools.com/xpath/default.asp 61

63 JSON XML can be very useful for data interchangeXML can be very useful for data interchange  When used with XSL or even CSS it can also result in very nicely formatted documents  However, it is a bit wordy Tree must be parsed to access nodesTree must be parsed to access nodes To be general, syntax requires extra typingTo be general, syntax requires extra typing –Ex: item.childNodes[0].nodeValue  Perhaps we can send data that is more easily parseable? 62

64 JSON JSONJSON  JavaScript Object Notation Data interchange format that allows text to be converted into simple Javascript objects (and back)Data interchange format that allows text to be converted into simple Javascript objects (and back)  We can use this to send data from a server to an AJAX client The client then generates Javascript primitive objects by processing the text dataThe client then generates Javascript primitive objects by processing the text data 63

65 JSON  Idea: We can think of JS objects as a set of key / value pairsWe can think of JS objects as a set of key / value pairs Ex:Ex:CD.idCD.titleCD.artistCD.votes We can then access the object as a single entity, or we can access the individual instance variablesWe can then access the object as a single entity, or we can access the individual instance variables 64

66 JSON  JSON formats text data into key, value pairs that can easily be parsed and converted back into Javascript objects  On the PHP SERVER we can: Put the data into a keyed PHP array:Put the data into a keyed PHP array: –$A[‘id’] = 1; –$A[‘title’] = ‘Fear of Music; … We can then call the function:We can then call the function: –json_encode() to convert the data into the JSON format –This puts the data into a list of key:value pairs that can be sent to the client 65

67 JSON  On the CLIENT we can Use the JSON.parse() function that will convert the JSON text into a simple Javascript objectUse the JSON.parse() function that will convert the JSON text into a simple Javascript object If we want a pseudo-typed object we can then pass the data to a constructorIf we want a pseudo-typed object we can then pass the data to a constructor  See: http://en.wikipedia.org/wiki/JSONhttp://en.wikipedia.org/wiki/JSONhttp://en.wikipedia.org/wiki/JSON http://www.json.org/js.htmlhttp://www.json.org/js.htmlhttp://www.json.org/js.html CDpoll-sortjson.php, tabulate-json.phpCDpoll-sortjson.php, tabulate-json.php 66

68 JSON with JQuery  As with XML, JQuery guesses on the return 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 return headerRather, it is a deduction based on the return header See CDpoll-jqjson.phpSee CDpoll-jqjson.php  Let’s look at a FINAL (yes, it is true!) version of the CD poll This one also allows sorting by individual columnsThis one also allows sorting by individual columns 67

69 APIs The Web is FULL of data!The Web is FULL of data!  Many many many sites have data that is accessible in various ways  We can set up our sites to access this data in interesting / useful ways Ex: Google Maps allows location information to be integrated into a Web siteEx: Google Maps allows location information to be integrated into a Web site –https://developers.google.com/maps/documentation/javascript/ 3.exp/reference https://developers.google.com/maps/documentation/javascript/ 3.exp/referencehttps://developers.google.com/maps/documentation/javascript/ 3.exp/reference Ex: Many weather sites have APIsEx: Many weather sites have APIs –Ex: http://apidev.accuweather.com/developers/ http://apidev.accuweather.com/developers/ Ex: BreweryDB allows access to beer and brewery informationEx: BreweryDB allows access to beer and brewery information –http://www.brewerydb.com/developers/docs http://www.brewerydb.com/developers/docs 68

70 APIs See: http://www.programmableweb.com/category/all/apisSee: http://www.programmableweb.com/category/all/apis http://www.programmableweb.com/category/all/apis Generally, accessing an API is straightforwardGenerally, accessing an API is straightforward  Typically users must request access to the API via a token or key  Individual requests send the key plus the request details  Responses are sent back in some standard format Ex: XML, JSON, etcEx: XML, JSON, etc 69

71 APIs  Note that we need to do this on the server side since AJAX requests are not allowed cross domain requests Let’s look at a simple example we have already seen:Let’s look at a simple example we have already seen:  ISBNDB This is a site which allows users to look up information about booksThis is a site which allows users to look up information about books Searches can be done via ISBN, Author, Title, etcSearches can be done via ISBN, Author, Title, etc See handout and examplesSee handout and examples 70

72 Client-Side Storage Consider persistent data on the serverConsider persistent data on the server  We can keep session data in (ex.) PHP session variables Persistent for current usePersistent for current use  We can keep long-term data in files or in a database  We have discussed both of these at length What about the client?What about the client?  So far the only persistent data we have on the client is cookies 71

73 Client-Side Storage  Initial purpose of cookies was to convey information from the client to the server So even though the data was stored on the client, cookies were not really used by the clientSo even though the data was stored on the client, cookies were not really used by the client  However, cookies are accessible to the client so we can look at them and even create them locally if we wish With the increase in client-side scripting, we may want to access / create / utilize cookies to help make decisions in our Javascript programsWith the increase in client-side scripting, we may want to access / create / utilize cookies to help make decisions in our Javascript programs 72

74 Client-Side Storage We can also manipulate cookies’ values that are utilized during AJAX requests to the serverWe can also manipulate cookies’ values that are utilized during AJAX requests to the server –See jq-cookie.html –Note that here we are using a JQuery plug-in to allow for easy cookie manipulation »These are GREAT but if you are using them make sure you have the.js code accessible »There are MANY other JQuery plug-ins available »Google to see some If we really wanted to, we could use cookies exclusively client-side if we wantedIf we really wanted to, we could use cookies exclusively client-side if we wanted –Maintain / update persistent data for use by our scripts –See jqex4-cookie.html 73

75 Client-Side Storage  However, cookies have some of the same drawbacks when used on the client 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 cookies –Must recall / extract each one  So, cookies are fine and useful, but it would be nice if we had another option for client- side storage 74

76 Client-Side Storage Is there an alternative?Is there an alternative?  With HTML 5 – yes!  We can now keep client-side data in a fashion very similar to that of server-side data  We have two global variables that are incorporated into our browser window and which can be accessed / updated from our scripts: sessionStoragesessionStorage –Keeps data for current browser session (while window or tab remains open) 75

77 Client-Side Storage localStoragelocalStorage –Keeps data indefinitely  Both of these variables store data in key / value pairs Both the key and value must be strings, which could be a problem if we want to store more complex dataBoth the key and value must be strings, which could be a problem if we want to store more complex data Solution:Solution: –Use JSON.stringify() to convert from Javascript objects to JSON in order to store –Use JSON.parse() to convert back when accessing –A bit of work but the best we can do right now 76

78 Client-Side Storage The amount of storage available does not have a predefined limitThe amount of storage available does not have a predefined limit –However, many browsers specify a limit per domain, or overall –Usually it is several Mb per domain  Syntax: Both localStorage and sessionStorage can be accessed as Javascript objectsBoth localStorage and sessionStorage can be accessed as Javascript objects Functions which are of interest to us:Functions which are of interest to us: –setItem(key, value) »Puts the value at the specified key »Key and value must both be a string, but they could be JSON (stringified objects) 77

79 Client-Side Storage –getItem(key) »Retrieve the value at the specified key »If no value is there, it returns null –removeItem(key) »Remove the item at the given key »Will be set back to null –length »Note that it is NOT a function – rather it is an attribute value »Returns the number of values stored in the storage –key(index) »Return the key at a given index »Index values of keys are maintained in some sequential way »Thus, to get all keys in localStorage we can iterate the the indexes from 0 to length For more info, seeFor more info, see https://developer.mozilla.org/en/DOM/Storage 78

80 Client-Side Storage  Let’s look at another example Same as jqex4.html but now each poll we take will be saved into local storageSame as jqex4.html but now each poll we take will be saved into local storage User can choose to see any previous resultsUser can choose to see any previous results See: jqex4-local.htmlSee: jqex4-local.html  Also see CS 1520 Home Page localStorage is used to keep user’s style preferencelocalStorage is used to keep user’s style preference 79


Download ppt "1 Course Notes for CS1520 Programming Languages Part B By John C. Ramirez Department of Computer Science University of Pittsburgh."

Similar presentations


Ads by Google