Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 79

Course Notes for

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

1
• These 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 form
• Material from these notes is obtained from various sources, including,
but not limited to, the following:
4 Programming the World Wide Web, multiple editions, by Robert Sebesta
(AW)
4 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/

2
Lecture 1: Intro to JavaScript

• What is JavaScript?
4 Language developed by Netscape
4 Primary purpose is for "client-end"
processing of HTML documents
• JavaScript code is embedded within the html
of a document
• An 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 page
3
Lecture 1: JavaScript Basics

• How to include JavaScript in html?


4 JavaScript programs require the <SCRIPT>
tag in .html files
<script type = "text/javascript">
ACTUAL JavaScript code here
</script>

4 These can appear in either the <HEAD> or


<BODY> section of an html document
• Functions and code that may execute multiple
times is typically placed in the <HEAD>
– These are only interpreted when the relevant
function or event-handler are called

4
Lecture 1: JavaScript Basics

• Code that needs to be executed only once, when


the document is first loaded is placed in the
<BODY>
4 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 text
– This way browsers that do not recognize JavaScript
will look at the programs as comments

4 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 problem
5
Lecture 1: JavaScript Basics

4 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 file
• Use the src option in the tag
<script type = "text/javascript" src =
"bogus.js"></script>
– 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

6
Lecture 1: Simple Example

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

7
Lecture 1: JavaScript Variables

4 JavaScript variables have no types


• Type is determined dynamically, based on the value
stored
– This is becoming familiar!
– The typeof operator can be used to check type of a
variable

4 Declarations are made using the var keyword


• Can be implicitly declared, but not advisable
• Declarations outside of any function are global
• Declarations within a function are local to that
function
• Variables declared but not initialized have the value
undefined
8
Lecture 1: JavaScript Variables

4 Variable identifiers are similar to those in


other languages (ex: Java)
• Cannot use a keyword
• Must begin with a letter, $, or _
– Followed by any sequence of letters, $, _ or digits
• Case sensitive

9
Lecture 1: JavaScript Expressions

4 Numeric operators in JavaScript are similar


to those in most languages
+, –, *, /, %, ++, --
• Precedence and associativity are also fairly
standard
4 Strings
• Have the + operator for concatenation
• Have a number of methods to do typical
string operations
– charAt, indexOf, toLowerCase, substring
• Looks kind of like Java – intentionally

10
Lecture 1: JavaScript Expressions

4 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 string
• If 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 parseFloat
– Again looks like Java

4 See ex2.html

11
Lecture 1: Control Statements

• Relational operators:
==, !=, <, >, <=, >=
• The above allow for type coercion. To prevent
coercion there is also
===, !==
– Similar to PHP

• Boolean operators
&&, ||, !
• &&, || are short-circuited (as in Java and PHP)
– Discuss

12
Lecture 1: Control Statements

• Control statements similar to Java


4 if, while, do, for, switch
• Variables declared in for loop header are
global to the rest of the script

• Functions
4 Similar to Java functions, but
• Header is somewhat different
function name(param_list)
– Return type not specified (like PHP, since JS has
dynamic typing)
– Param types also not specified

13
Lecture 1: Functions

• Functions execute when they are called, just as


in any language
• To allow this, function code should be in the
<HEAD> section of the .html file
• Variables declared in a function are local to the
function
• Parameters 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.html
14
Lecture 1: Array Objects

4 More relaxed version of Java arrays


• Size can be changed and data can be mixed
• Cannot use arbitrary keys as with PHP arrays
4 Creating arrays
• Using 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 argument
var B = new Array(50);
• Using square brackets to make a literal
var C = ["we", "can", 50, "mix", 3.5, "types"];

15
Lecture 1: Array Objects

4 Array Length
• Like 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 array
• Unlike Java, length can be changed by the
programmer
• Actual 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

16
Lecture 1: Array Objects

• Array Methods
4 There are a number of predefined operations
that you can do with arrays
– concat two arrays into one
– join array items into a single string (commas between)
– push, pop, shift, unshift
» Push and pop are a "right stack"
» Shift and unshift are a "left stack"
– sort
» Sort by default compares using alphabetical order
» To sort using numbers we pass in a comparison function
defining how the numbers will be compared
– reverse
» Reverse the items in an array

17
Lecture 1: Array Objects

• These operations are invoked via method


calls, in an object-based way
– Also many, such as sort and reverse are mutators,
affecting the array itself

4 JavaScript also has 2-dimensional arrays


• Created as arrays of arrays, but references
are not needed
4 see ex4.html

18
Lecture 1: JavaScript Objects

• JavaScript is an object-based language


4 It is NOT object-oriented
4 It has and uses objects, but does not support
some features necessary for object-oriented
languages
• Class 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/column80/

19
Lecture 1: JavaScript Objects

4 JavaScript objects are actually represented as


property-value pairs
• Actually similar to keyed arrays in PHP
• The 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:
var my_tv = new Object();
my_tv.brand = ”Samsung";
my_tv.size = 46;
my_tv.jacks = new Object();
my_tv.jacks.input = 5;
my_tv.jacks.output = 2;

20
Lecture 1: JavaScript Objects

• Note that the objects can be created and their


properties can be changed dynamically
• Also, 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 objects
function TV(brand, size, injacks, outjacks)
{
this.brand = brand;
this.size = size;
this.jacks = new Object();
this.jacks.input = injacks;
this.jacks.output = outjacks;
}

var my_tv = new TV(”Samsung”, 46, 5, 2);

21
Lecture 1: JavaScript Objects
• Once 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: <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 ex5.html

22
Lecture 1: Javascript Objects

• We can do a lot with Javascript objects


4 Even though Javascript is not truly object-
oriented, we can program in an object-based
way
• Encapsulating data and methods within
objects
• Utilizing methods for operations on the
objects
• See ex6.html
4 We will be using Javascript objects a lot with
client-side programming
23
Lecture 1: Regular Expressions

4 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)
• 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.html
24
Lecture 2: DOM

• The Document Object Model


4 Developed by W3C (World-Wide Web Consortium)
• http://www.w3c.org/DOM/
4 Specifies the contents of Web documents in an
object-oriented way
• Allows 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 it
• It is still being updated / revised
4 We will not cover this completely – investigate!
25
Lecture 2: DOM

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

4 DOM 1, 2, 3
• Formal specifications of model and
functionality
• Each builds on / improves previous
4 DOM 4 is being finalized
4 With recent browsers there is general DOM
compatibility
• IE 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 work
27
Lecture 2: Events

4 With documents DOM specifies events and event


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

• document refers to the top-level document


4 Each document has access to its properties and to
the components that are declared within it
• Ex: title, URL, forms[], images[]
• Attributes with IDs can also be specified by ID (from
DOM 1)
4 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
overall
29
Lecture 2: DOM and Events

– Ex: Checking form correctness before it is submitted

4 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 events
4 See Sebesta Table 5.1 for events and tag
attributes and Table 5.2 for the tags that have a
given attribute
4 Similar in idea to Java, we assign event handling
code to the tag attributes, and the code executes
when the event occurs
30
Lecture 2: Events

• We can also attach events in Javascript


4 In DOM 0, events are attached in an “inline” way:
• Ex: theElement.onclick = functionName
4 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)
– Where opt is a boolean to determine if the event is “captured”
or “bubbles”
» See: http://en.wikipedia.org/wiki/DOM_Events

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


– It has its own, similar model

31
Lecture 2: DOM and Events

4 Ex: Event mouseover occurs when the


mouse is place over a displayed element
• Elements 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 called
<input type = "radio" name = "choice" value = "1"
onmouseover = "showChoice(1)">

• We can define showChoice however we'd like


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

32
Lecture 2: Example: Pre-processing a Form

• A very common client-side operation is


pre-processing a form
4 Ensure that fields are filled and formatted
correctly, so server does not have to
• Saves load on the server, saves time and
saves bandwidth
• We 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

33
Lecture 2: Example: Pre-processing a form

• We can check individual components as they


are entered as well
– Ex: <input type = "text"> has the onchange
attribute
» Triggered when contents are changed and focus
changes
– Ex: <input type = "radio"> has the onclick
attribute
» Triggered when the radio button is clicked with the
mouse

• See 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!

34
Lecture 2: Processing Multiple Forms and Multiple Submits

4 Web pages can also have multiple forms


• These 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 accordingly
– See mform.html and mform.php

4 Similarly, we can have multiple submits of a


single form
• See also msub.html and msub.php
4 One more example demonstrating DOM
• See ex9.html
35
Lecture 3: AJAX

• Asynchronous 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 that
• It 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 app
• See: http://en.wikipedia.org/wiki/AJAX
http://developer.mozilla.org/en/docs/AJAX
36
Lecture 3: AJAX

4 Let's look at a few details and some simple


examples
• You may also want to research it on your own
4 AJAX centers around the XMLHttpRequest
object
4 This object allows the client to connect to a
server and to respond to the reply once it has
become available
4 There is a lot that can be done with this,
especially in conjunction with XML and JSON –
we will mention these later
37
Lecture 3: AJAX

4 It is a bit tricky to use, and is not consistent


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

38
Lecture 3: AJAX

• onreadystatechange
– 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)
» 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

39
Lecture 3: AJAX

• 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
• readyState
– Attribute that stores the current state of the object
– Changes throughout the execution:
» 0  uninitialized
» 1  loading
» 2  loaded
» 3  interactive
» 4  complete

40
Lecture 3: AJAX

• status
– 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
• responseType
– What type of data did the server send back to the
client?
• response, responseText, responseXML
– Get the data that was returned
– We can parse this to utilize the data to update our
page

41
Lecture 3: AJAX

4 Big Picture:
• The 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
page
• Show on board
4 Let's look at a simple example
• MozDemo.html – from Mozilla devel. site
– Just demonstrates the basics of AJAX

42
Lecture 3: AJAX

4 Ok, that example was very simple


4 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()?
– Only works during initial rendering of the page
• 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
– Idea: If we treat our local Web page as an object,
then we can modify in response to data sent back
by the server

43
Lecture 3: AJAX and DOM

4 For example, consider the methods /attributes


for accessing/modifying data in an HTML table:
• First 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 row
– We can use the rows[] array
• We may then want a specific cell
– We can use the cells[] array from the row
• And 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.php


44
Lecture 3: AJAX and DOM

4 However, what if we want to make more


significant changes?
4 Ex: Add a new row to a table
• Get the table again
• Insert a new row
– Use insertRow()
• Insert a new cell
– Use insertCell()
• Add the data to the cell
– Use createTextNode() for text
» More complex for the radio button – see handout
– Use appendChild()

45
Lecture 3: AJAX and DOM

• Caution:
4 Be aware that AJAX can update data
locally and can cause inconsistency with
data at server
4 For example, consider 2 clients both running
CDpoll.php
• Client 1 then adds a new write-in choice
• Client 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
Lecture 3: AJAX and DOM

4 So we need to either
• Get 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
occasionally
– Updates from one client do not affect another
• Use the server to read from but not to write to
– Consistency is not a problem if data does not
change

47
Lecture 3: Updating the Page

4 One way to keep a page updated is to have


it automatically connect to a server for new
information
4 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
4 This can be done in a fairly simple way
utilizing:
• AJAX requests
• A Javascript timer
48
Lecture 3: Updating the Page

4 When the page is loaded the timer starts


4 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 request
4 See CDpoll-update.php and
tabulate-update.php
• Note that we now have some consistency
concerns to consider

49
Lecture 3: Updating the Page

• 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 twice
• Note that the DB will still be consistent
– What is not consistent is the client
• We can prevent this with some simple
synchronization
– See CDpoll-update.php

50
Lecture 3: What about the “X”?

• So far our AJAX examples have used


responseText
• Where does the XML come in?
• AJAX these days also utilizes JSON
objects as a response
4 What are these and how are they used?

• We will talk about XML now and JSON a


bit later on

51
What about the X?

• The “X” in AJAX is for XML


4 The result of a send() to a server can be
obtained
• As text using responseText attribute
• As XML using responseXML attribute
4 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
difference

52
The X

4 Once we have the XML document, we can


parse, manipulate, update, etc. using DOM
4 DOM for XML is similar to DOM for HTML
4 One function that is used a lot with XML is
getElementsByTagName()
4 Allows access to any tags, regardless of that they
are

4 See
• http://www.w3schools.com/xml/xml_dom.asp
• http://www.w3schools.com/xml/xml_server.asp
• Many others as well if you search the Web

4 Let’s look at a couple examples

53
The X

• Idea:
4 First we get the document
• var xmldoc =
httpReqObject.responseXML.documentElement
• Then 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
The X

4 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.asp
4 Let's look at some very simple examples
• Simple Joke display program
• EXTREMELY primitive RSS reader
• ISBN book lookup
• CD poll (yet ANOTHER version!!)

55
The X

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


version
4 This time we will change a few things:
1)Get rid of PHP entirely
• Think 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
The X

2) Keep the data sorted


• Up until now the CDs were in the order
submitted
• No reason to keep them that way
• Storing 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 form
– This leads to point 3)

57
The X

3) Store the CDs locally on the client


• Up 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 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
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 table
• But 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

4 See CDpoll-sortxml.php

59
XSLT

• We discussed using XSL style sheets to


format XML documents
4 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 response
• We 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
XSLT

• We 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:
– 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

61
JSON

• XML can be very useful for data


interchange
4 When used with XSL or even CSS it can also
result in very nicely formatted documents
4 However, it is a bit wordy
• Tree must be parsed to access nodes
• To be general, syntax requires extra typing
– Ex: item.childNodes[0].nodeValue

4 Perhaps we can send data that is more


easily parseable?

62
JSON

• JSON
4 JavaScript Object Notation
• Data interchange format that allows text to
be converted into simple Javascript objects
(and back)
4 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 data

63
JSON

4 Idea:
• We can think of JS objects as a set of key /
value pairs
• Ex:
CD.id
CD.title
CD.artist
CD.votes
• We can then access the object as a single
entity, or we can access the individual
instance variables

64
JSON

4 JSON formats text data into key, value pairs


that can easily be parsed and converted
back into Javascript objects
4 On the PHP SERVER we can:
• Put the data into a keyed PHP array:
– $A[‘id’] = 1;
– $A[‘title’] = ‘Fear of Music;

• 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
JSON

4 On the CLIENT we can


• Use 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 constructor
4 See:
• http://en.wikipedia.org/wiki/JSON
• http://www.json.org/js.html
• CDpoll-sortjson.php, tabulate-json.php

66
JSON with JQuery

4 As with XML, JQuery guesses on the return


type and parses appropriately
• Note that this is not really a guess
• Rather, it is a deduction based on the return
header
• See CDpoll-jqjson.php
4 Let’s look at a FINAL (yes, it is true!) version
of the CD poll
• This one also allows sorting by individual
columns

67
APIs

• The Web is FULL of data!


4 Many many many sites have data that is
accessible in various ways
4 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 site
– https://developers.google.com/maps/documentation/javascript/
3.exp/reference
• Ex: Many weather sites have APIs
– Ex: http://apidev.accuweather.com/developers/
• Ex: BreweryDB allows access to beer and brewery
information
– http://www.brewerydb.com/developers/docs

68
APIs

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

4 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:
4 ISBNDB
• This is a site which allows users to look up
information about books
• Searches can be done via ISBN, Author, Title,
etc
• See handout and examples
70
Client-Side Storage

• Consider persistent data on the server


4 We can keep session data in (ex.) PHP session
variables
• Persistent for current use
4 We can keep long-term data in files or in a
database
4 We have discussed both of these at length

• What about the client?


4 So far the only persistent data we have on the
client is cookies
71
Client-Side Storage

4 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
client
4 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 programs

72
Client-Side Storage

• We 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 wanted
– Maintain / update persistent data for use by our
scripts
– See jqex4-cookie.html

73
Client-Side Storage

4 However, cookies have some of the same


drawbacks when used on the client that they
did on the server
• Limited size (4K)
• Kind of clunky to use / access
– To store lots of data we need lots of cookies
– Must recall / extract each one

4 So, cookies are fine and useful, but it would


be nice if we had another option for client-
side storage

74
Client-Side Storage

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

75
Client-Side Storage

• localStorage
– Keeps data indefinitely

4 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 data
• 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
Client-Side Storage

• The 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

4 Syntax:
• Both localStorage and sessionStorage can be
accessed as Javascript objects
• 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
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, see
https://developer.mozilla.org/en/DOM/Storage

78
Client-Side Storage

4 Let’s look at another example


• Same as jqex4.html but now each poll we
take will be saved into local storage
• User can choose to see any previous results
• See: jqex4-local.html
4 Also see CS 1520 Home Page
• localStorage is used to keep user’s style
preference

79

You might also like