Course Notes for
Programming Languages
Part B
John C. Ramirez
Department of Computer Science
University of Pittsburgh
• 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:
 Programming the World Wide Web, multiple editions, by Robert Sebesta
 JavaScript by Don Gossein (Thomson Learning)
Lecture 1: Intro to 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 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
Lecture 1: JavaScript Basics
• How to include JavaScript in html?
JavaScript programs require the <SCRIPT>
tag in .html files
<script type = "text/javascript">
ACTUAL JavaScript code here
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
Lecture 1: JavaScript Basics
• Code that needs to be executed only once,
when the document is first loaded is placed in
the <BODY>
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
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
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 file
• Use the src option in the tag
<script type = "text/javascript" src =
– 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
Lecture 1: Simple Example
<TITLE>First JavaScript Example</TITLE>
<H2>This line is straight HTML</H2>
<SCRIPT type = "text/javascript">
document.write("These lines are produced by<br/>");
document.write("the JavaScript program<br/>");
alert("Hey, JavaScript is fun!");
<H2>More straight HTML</H2>
<SCRIPT type = "text/javascript" src="bogus.js"></script>
Lecture 1: JavaScript Variables
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
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
• Variables declared but not initialized have the
value undefined
Lecture 1: JavaScript Variables
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
Lecture 1: JavaScript Expressions
Numeric operators in JavaScript are similar
to those in most languages
+, –, *, /, %, ++, -• Precedence and associativity are also fairly
• 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
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 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
See ex2.html
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
Lecture 1: Control Statements
• Control statements similar to Java
if, while, do, for, switch
• Variables declared in for loop header are
global to the rest of the script
• Functions
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
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
• 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
Lecture 1: Array Objects
More relaxed version of Java arrays
• Size can be changed and data can be mixed
• Cannot use arbitrary keys as with PHP arrays
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"];
Lecture 1: Array Objects
Array Length
• Like in Java, length is an attribute of all array
• 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
• 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
Lecture 1: Array Objects
• Array Methods
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
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
JavaScript also has 2-dimensional arrays
• Created as arrays of arrays, but references
are not needed
see ex4.html
Lecture 1: JavaScript Objects
• JavaScript 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
• Class inheritance and polymorphism not
– They can be “faked” but are not really there
Lecture 1: JavaScript Objects
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
• 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;
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);
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
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/>");
… = show_properties;
– See ex5.html
Lecture 1: Javascript Objects
• We can do a lot with Javascript objects
Even though Javascript is not truly objectoriented, we can program in an object-based
• Encapsulating data and methods within
• Utilizing methods for operations on the
• See ex6.html
We will be using Javascript objects a lot with
client-side programming
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)
• However, now the functions are methods
within a string object (similar to Java)
s =
s = "a man, a plan, a canal: panama";
loc =;
matches1 = s.match(/an/g);
matches2 = s.match(/\w+/g);
matches3 = s.split(/\W+/);
s.replace(/\W/g, "-");
– Note that match is similar to the PHP match function
» Returns the matched pieces as opposed to the nonmatched pieces (that split returns)
• See ex7.html
Lecture 2: DOM
• The Document Object Model
Developed by W3C (World-Wide Web Consortium)
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
We will not cover this completely – investigate!
Lecture 2: DOM
• History / Idea
HTML and XML documents consist of tags
Well-formatted documents (required in
XHTML and XML) can be viewed as a tree
• Ex:
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 functionality
Lecture 2: DOM
DOM 1, 2, 3
• Formal specifications of model and
• Each builds on / improves previous
DOM 4 is being finalized
With recent browsers there is general DOM
• 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
Lecture 2: Events
With documents DOM specifies events and event
• 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
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
Lecture 2: DOM and Events
• document 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[]
• Attributes with IDs can also be specified by ID (from
DOM 1)
Once we know the components, events and eventhandlers, 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
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 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
Lecture 2: Events
• We can also attach events in Javascript
In DOM 0, events are attached in an “inline” way:
• Ex: 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)
– Where opt is a boolean to determine if the event is
“captured” or “bubbles”
» See:
• Unfortunately, IE (up through IE8) does not use
– It has its own, similar model 31
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 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");
Lecture 2: Example: Pre-processing a Form
• A 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 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
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
» Triggered when contents are changed and focus
– Ex: <input type = "radio"> has the onclick
» Triggered when the radio button is clicked with the
• 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
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 side
• Idea 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.php
One more example demonstrating DOM
• See ex9.html
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:
Lecture 3: AJAX
Let's look at a few details and some simple
• You may also want to research it on your own
AJAX centers around the XMLHttpRequest
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
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 object
• Several useful attributes and methods are
associated with this object:
– see:
– Let's look at a few of them to see how they work
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
• 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
Lecture 3: AJAX
• send(data)
» Where "data" is a the information to be sent to the
» Can be formatted in various ways, with different
» 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:
Lecture 3: AJAX
• status
– Did everything work correctly?
200 – yes it did
404 – Not found
500 – internal server error
For more codes, see
• responseType
– What type of data did the server send back to the
• response, responseText, responseXML
– Get the data that was returned
– We can parse this to utilize the data to update our
Lecture 3: AJAX
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
• Show on board
Let's look at a simple example
• MozDemo.html – from Mozilla devel. site
– Just demonstrates the basics of AJAX
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()?
– 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:
– Idea: If we treat our local Web page as an object,
then we can modify in response to data sent back
by the server
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 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
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 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()
Lecture 3: AJAX and DOM
• Caution:
Be aware that AJAX can update data
locally and can cause inconsistency with
data at server
For example, consider 2 clients both running
• 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
Lecture 3: AJAX and DOM
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
– See CDpoll2.php and tabulate2.php
• Design our program in such a way that we
only need to “sync” with the server
– Updates from one client do not affect another
• Use the server to read from but not to write
– Consistency is not a problem if data does not
Lecture 3: Updating the Page
One way to keep a page updated is to have
it automatically connect to a server for new
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
• AJAX requests
• A Javascript timer
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 request
See CDpoll-update.php and
• Note that we now have some consistency
concerns to consider
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
• 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
– See CDpoll-update.php
Lecture 3: What about the “X”?
• So far our AJAX examples have used
• Where does the XML come in?
• AJAX 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 on
What about the X?
• The “X” in AJAX is for XML
The result of a send() to a server can be
• As text using responseText attribute
• As 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
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
Allows access to any tags, regardless of that they
• Many others as well if you search the Web
Let’s look at a couple examples
The X
• Idea:
First we get the document
• var xmldoc =
• Then we can access it via tags
var aTag =
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!
The X
Once we have the XML document we can
manipulate it in much the same way as the
html document
• See:
Let's look at some very simple examples
• Simple Joke display program
• EXTREMELY primitive RSS reader
• ISBN book lookup
• CD poll (yet ANOTHER version!!)
The X
• Let’s look at a (yet yet) another CD poll
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
– Couldn’t we use AJAX to “update” the entire table?
» Yes!
– This makes the page more streamlined / readable /
– See CDpoll-sortxml.php
The X
2) Keep the data sorted
• Up until now the CDs were in the order
• 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)
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
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
 See CDpoll-sortxml.php
• We 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 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
• 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
• Also see some references:
• XML can be very useful for data
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 nodes
• To be general, syntax requires extra typing
– Ex: item.childNodes[0].nodeValue
Perhaps we can send data that is more
easily parseable?
JavaScript Object Notation
• 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 data
• We can think of JS objects as a set of key /
value pairs
• Ex:
• We can then access the object as a single
entity, or we can access the individual
instance variables
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:
– $A[‘id’] = 1;
– $A[‘title’] = ‘Fear of Music;
• We can then call the function:
– json_encode() to convert the data into the JSON
– This puts the data into a list of key:value pairs that
can be sent to the client
On the CLIENT we can
• Use the JSON.parse() function that will
convert the JSON text into a simple Javascript
• If we want a pseudo-typed object we can
then pass the data to a constructor
• CDpoll-sortjson.php, tabulate-json.php
JSON with JQuery
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
• See 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
• 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 site
• Ex: Many weather sites have APIs
– Ex:
• Ex: BreweryDB allows access to beer and brewery
• See:
• Generally, accessing an API is
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
• Ex: XML, JSON, etc
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:
• This is a site which allows users to look up
information about books
• Searches can be done via ISBN, Author, Title,
• See handout and examples
Client-Side Storage
• Consider persistent data on the server
We can keep session data in (ex.) PHP
session variables
• Persistent for current use
We can keep long-term data in files or in a
We have discussed both of these at length
• What about the client?
So far the only persistent data we have on
the client is cookies
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
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
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
– See jqex4-cookie.html
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)
• Kind 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 clientside storage
Client-Side Storage
• 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
• sessionStorage
– Keeps data for current browser session (while
window or tab remains open)
Client-Side Storage
• localStorage
– 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 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
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
• 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)
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
Client-Side Storage
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
Also see CS 1520 Home Page
• localStorage is used to keep user’s style

CS 1520 Lecture Notes