Science Fair Project - Seton Hall University Pirate Server

Download Report

Transcript Science Fair Project - Seton Hall University Pirate Server

AJAX – Async JavaScript and XML
Bert Wachsmuth
Review
Last-Last Time
 Internet, IP addresses, ports, client-server, http, smtp
 HTML, XHTML, XML
 Style Sheets, external, internal, inline, selector, properties, ids, classes, elements
 MS Expression Web, local and remote web site, synchronization, Dynamic Web Template
Last Time
 Dynamic Web Pages: client-side and server-side programming
 Intro to JavaScript: basic operations, conditionals, loops,
functions, dialog boxes
 Intro to the DOM: defining an element, replacing innerHTML,
refreshes without reloading
Homework
Exercise:
 Come up with a math problem that can be the basis of a
JavaScript program/simulation
 Enhance our “random cannon shoot” program
DOM – Magic Trick (1)
<html>
<head>
<title>A Magic Trick</title>
</head>
<body>
<h1>A Magic Trick</h1>
<p><img src="topHat.gif"></p>
</body>
</html>
DOM – Magic Trick (2)
<html>
<head>
<title>A Magic Trick</title>
<script language="javascript" type="text/javascript">
function magic()
{
var image = document.getElementById("hat");
}
</script>
</head>
<body>
<h1>A Magic Trick</h1>
<p><img src="topHat.gif" id="hat" onclick="magic"></p>
</body>
</html>
DOM – Magic Trick (3)
...
<script language="javascript" type="text/javascript">
function magic()
{
var image = document.getElementById("hat");
image.setAttribute("src", "topHat.gif");
}
</script>
</head>
<body>
<h1>A Magic Trick</h1>
<p><img src="topHat.gif" id="hat" onclick="magic"></p>
</body>
</html>
DOM – Magic Trick (4)
<script ...>
var rabbitVisible = false;
function magic()
{
var image = document.getElementById("hat");
if (rabbitVisible)
{
image.setAttribute("src", "topHat.gif");
}
else
{
image.setAttribute("src", "rabbit-hat.gif");
}
rabbitVisible = !(rabbitVisible);
}
Our Extended Example
Switching Styles
We learned how to attach multiple style sheets to a document, which
all ‘cascade’ into one style. You can also define alternate style sheets
so that the user can switch between them to give a page the look they
prefer. You can, for example:
 use a default style sheet for your average user
 provide an alternate style sheet with large print for users with poor
eye sight
 provide another style sheet in gray-scale to use for printing
 use yet another style sheet to optimize your content to viewers with
small devices (smart phones)
Switching Styles (2)
File style1.css
File style2.css
/* Using width of screen */
body {
margin: 10px;
width: 100%;
}
/* For small device */
body {
margin: 10px auto;
width: 480px;
}
h1 {
background-color: blue;
color: yellow;
}
h1 {
background-color: yellow;
color: blue;
}
.justified
{
text-align: left;
}
.justified
{
text-align: right;
}
Switching Styles (3)





Create a simple HTML file
Add a header 1
Add some text in a paragraph with class justified
Attach the first style sheet
Switch to code view (if not already) and add second style sheet:
<link href="style1.css" rel="stylesheet" type="text/css"
title="Default Style" />
<link href="style2.css" rel="alternate stylesheet" type="text/css"
title="Mobile Style" />
Switching Styles (4)
 View your page in Firefox (not IE
 Select “View | Page Style” and pick you alternate style.
Pretty cool, but there are two disadvantages:
 the new style does not ‘stick’ and has to be re-selected every time
 this type of style switching is not supported by Internet Explorer!!
We need to develop a method to switch styles that remedies both
problems. That’s where JavaScript comes in!
Switching Styles (5)
Give the two style tags an ID so that we can reference them in the DOM:
<link href="style1.css" rel="stylesheet" type="text/css"
title="Default Style" id="default" />
<link href="style2.css" rel="alternate stylesheet"
type="text/css"
title="Mobile Style" id="mobile" />
Now all we need is a trigger to call the function. Add:
<form>
<input type="button" value="Switch style"
onclick="switch_style()" />
</form>
Switching Styles (6)
Now we can add the script in the header:
function switch_style()
{
style_default = document.getElementById("default");
style_mobile = document.getElementById("mobile");
if (style_default.disabled)
{
style_default.disabled = false;
style_mobile.disabled = true;
}
else
{
style_default.disabled = true;
style_mobile.disabled = false;
}
}
Cookies
 Cookies are small chunks of data that are saved by your browser.
 One web page can cause your browser to save data in a cookie and
the same or another page can later retrieve the saved data.
 The JavaScript cookie is a document object with the following
parameters:






name: the name of the cookie
value: the value of the cookie (i.e. the data it stores)
expires: the date/time when the cookie expires automatically
path: the path of a cookie
domain: the name of the server that created the cookie
secure: whether to use encryption to read/set cookie
Cookie Restrictions
To help protect your computer, cookies follow some rules:
 Only small amounts of data can be stored in a cookie
 Cookies are available via JavaScript only to the domain used when the cookie
was created
 Cookies are available only to files in the same directory the cookie was created
in (to make a cookie available to all files use as path “/”)
 Cookies can be manually manipulated in a web browser. In Firefox:
 Tools -> Options -> Privacy -> Show Cookies will show all cookies stored
 Tools -> Options -> Privacy lets you decide whether browser accepts
cookies
 Tools -> Clear Private Data lets you delete all stored cookies
Displaying all Cookies
 Start with a new HTML document
 Add the following function to the header:
function showCookies()
{
alert("My cookies: " + document.cookie);
}
 Add an appropriate trigger to the body (perhaps a button)
Setting a Cookie
 To set a cookie, you assign an appropriate value to
document.cookie
 Minimum cookie: name=value;expires=date;path=mypath
function setCookie(name, value, expireDays)
{
var expires = new Date();
expires.setDate(expires.getDate() + expireDays);
var myCookie= name + "=" + escape(value) +
";expires=" + expires.toGMTString() +
";path=/";
document.cookie = myCookie;
alert("Set cookie:" + myCookie);
}
Deleting a Cookie
 To delete a cookie is easy: we simply set the name of the cookie to
an empty string and expire it yesterday.
 Even better, we can use the setCookie method to do the work
for us:
function delCookie(name)
{
alert("Delete Cookie: " + name);
setCookie(name, "", -1);
}
Retrieving a Cookie
 document.cookie consists of “name=value” pairs, separated by semi-colons
and leading spaces (or it is empty)
 Split it at the semicolons into an array, each entry now a name=value pair.
 Go through the array, split each entry at the equal sign and check the name
 Splitting is easy thanks to the build-in split function
 To remove extra leading spaces, we define:
function removeLeadingSpace(s)
{
while ((s != null) && (s.length > 0) &&
(s.charAt(0) == ' '))
s = s.substring(1,s.length);
return s;
}
Retrieving a Cookie (2)
function getCookie(name)
{
if ((document.cookie == null) || (document.cookie == ""))
{
return "";
}
else
{
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++)
{
var cookie = cookies[i].split('=');
if (removeLeadingSpace(cookie[0]) == name)
{
return unescape(cookie[1]);
}
}
return "";
}
}
External JavaScript File
 We have created universally useful functions to work with cookies.
 Put these functions in a separate file, clean up the codes,, and add
comments for better readability
 Save as “cookiecutters.js” in a directory of your choice on your web site
 Now we can use our code in any page dealing with cookies. By loading
JavaScript from an external file:
<script language="javascript" type="text/javascript"
src="cookiecutter.js">
</script>
 Of course we need to extensively test our new code
Testing Cookie Code
<form name="form">
<p>Cookie name: <input type="text" name="name" /></p>
<p>Cookie value: <input type="text" name="content" /></p>
<p>
<input type="button" value="Show cookies"
onclick="showCookies()" />
<input type="button" value="Set cookie"
onclick="setCookie(document.form.name.value,
document.form.content.value,1)" />
<input type="button" value="Get cookie"
onclick="alert(getCookie(document.form.name.value))" />
<input type="button" value="Delete cookie"
onclick="delCookie(document.form.name.value)" />
</p>
</form>
Homework
 Add appropriate comments, version and author info, disclaimer,
copyright info, licensing info, etc. to our library of cookiehandling functions.
 Use our new library cookiecutter.js to create a page that
switches styles and remembers the style last selected so that when
you later return to the page, it will use the style you selected last.
Timers and Recursion

JavaScript provides easy access to a timer via the window functions
setTimeout(‘function()’, millisecs) and clearTimeout(var)
<head>
<script language="javascript" type="text/javascript">
function delayedAlert()
{
var timer = window.setTimeout("alert('Time is up')", 5000);
}
</script>
</head>
<body
<input type="button" value="Start timer"
onclick="delayedAlert()" />
</form>
</body>
Count-Down Timer (1)
<head> …
</head>
<body>
<h1>Count down</h1>
<p>Count: <span id="output"></span></p>
<form>
<input type="button" value="Countdown" onclick="countdown()" />
<input type="button" value="Emergency Stop"
onclick="stop_countdown()" />
</form>
</body>
Count-Down Timer (2)
var counter = 20;
var timer = null;
function countdown()
{
var outputField = document.getElementById("output");
outputField.innerHTML = counter + " seconds";
counter--;
if (counter >= 0)
timer = window.setTimeout("countdown()", 1000);
else
{
alert('Lift-Off');
counter = 20;
}
}
function stop_countdown()
{
window.clearTimeout(timer);
alert("Countdown interrupted");
}
Falling Body Problem
 Investigate how long it will take for an object to hit the ground if it
is dropped from an airplane at a height of 10 km, and what is its
speed on impact.
 Situation 1: neglect air resistance and employ a calculus solution
 Situation 2: neglect air resistance and employ simulation
 Situation 3: take air resistance into account and use a simulation
The HTML Code
<h1>Falling Object Investigation</h1>
<p>Press the <tt>drop</tt> button to simulate the drop of object from a
height of 10 km . The values are updated every 0.1 seconds.</p>
<ul>
<li>Time: <span id="time">0</span> sec.</li>
<li>Height: <span id="height">10000</span> meter</li>
<li>Speed: <span id="speed">0</span> meter/second</li>
</ul>
<form>
<input type="button" value="Drop" onclick="drop()" />
</form>
var
var
var
var
timer = null;
init_height = 10000;
delta_t = 0.1;
g = 9.98;
No Air, Calculus
var t = 0;
var height = init_height;
var speed = 0;
function drop()
{
t = t + delta_t;
speed = -g*t;
height = init_height - 0.5*g*t*t;
document.getElementById("time").innerHTML = t;
document.getElementById("height").innerHTML = height;
document.getElementById("speed").innerHTML = speed;
if (height >= 0)
timer = window.setTimeout("drop()", delta_t*1000);
else
alert("Hit the ground");
}
var
var
var
var
timer = null;
init_height = 10000;
delta_t = 0.1;
g = 9.98;
No Air, Simulation
var t = 0;
var height = init_height;
var speed = 0;
function drop()
{
t = t + delta_t;
speed = speed - g*delta_t;
height = height + speed*delta_t;
document.getElementById("time").innerHTML = t;
document.getElementById("height").innerHTML = height;
document.getElementById("speed").innerHTML = speed;
if (height >= 0)
timer = window.setTimeout("drop()", delta_t*1000);
else
alert("Hit the ground");
}
var
var
var
var
var
timer = null;
init_height = 10000;
delta_t = 0.1;
g = 9.98;
k = 0.5;
Air resistance, simulation
 note this new constant of proportionality
var t = 0;
var height = init_height;
var speed = 0;
function drop()
{
t += delta_t;
speed = speed - (g + k*speed)*delta_t;
height = height + speed*delta_t;
document.getElementById("time").innerHTML = t;
document.getElementById("height").innerHTML = height;
document.getElementById("speed").innerHTML = speed;
if (height >= 0)
timer = window.setTimeout("drop()", delta_t*1000);
else
alert("Hit the ground");
}
The XMLHttpRequest Object
 At the heart of most data-oriented Web 2.0 pages like Google
Maps or Facebook is the XMLHttpRequest. It lets you load data:
 without reloading the page and
 synchronously or asynchronously
 It does have some limitations:
 IE 7, IE 8, and Firefox 2 and above handle XMLHttpRequest
similarly
 IE 5 and IE 6 handle XMLHttpRequest differently
 Really old browsers do not handle XMLHttpRequest at all
 XMLHttpRequest can only load data from the same server it is
coming from
 XMLHttpRequest cannot load data from a local disk at all
Need XML Data
 To experiment with XMLHttpRequest we need access to data in
XML format.
 Could try, for example, to use weather info provided by Google:
http://www.google.com/ig/api?weather=Frankfurt,Germany
 Google makes this data available just fine, and it is in perfect XML
format
However, we are unable to use it for our own JavaScript weatherforecast program – why?
Our own XML Data
File addressdata.xml
<xml>
<addressbook>
<address>
<name>Bert Wachsmuth</name>
<email>[email protected]</email>
</address>
<address>
<name>Silke von der Emde</name>
<email>[email protected]</email>
</address>
</addressbook>
</xml>
Simple Use
function showData()
{
var xml = new XMLHttpRequest();
xml.open("GET", "addressdata.xml", false);
xml.send("");
var xmlDoc = xml.responseXML;
var names = xmlDoc.getElementsByTagName("name");
var mails = xmlDoc.getElementsByTagName("email");
for (var i = 0; i < names.length; i++)
{
var name = names[i ].childNodes[0].nodeValue;
var mail = mails[i].childNodes[0].nodeValue;
document.writeln("<li>" + name + "(" + mail + ")</li>");
}
}
Better Use

Library to load XML data across browsers:
http://courses.shu.edu/spring09/CEPS0100/wachsmut/JavaScript/xmltools.js

Use index variable to track current address and functions as follows:
http://courses.shu.edu/spring09/CEPS0100/wachsmut/AJAX/addressbook.html
var
var
var
var
names = null;
emails = null;
recno = 0;
rectot = 0;
function
function
function
function
function
loadData()
showRecord()
nextRecord()
prevRecord()
findRecord()
//
//
//
//
an array of all names
an array of all emails
current record displayed
total records available
//
//
//
//
//
loads data file and sets names and emails arrays
displays the current record
increments recno and calls showRecord
decrements recno and calls showRecord
prompts for name and searches names array
Google’s Search API
 Google does provide XML data – even to its flagship “search” data
 It also provides suitable JavaScript functions
 Both data and JavaScript are coming from the same domain, so
there are no security restrictions!
 For details, check:
http://code.google.com/apis/ajaxsearch/
 or for even more information, check:
http://code.google.com/apis/ajax/
Google's Search API
<script src="http://www.google.com/jsapi"
type="text/javascript">
</script>
<script language="Javascript" type="text/javascript">
google.load('search', '1');
function loadSearch()
{
var searchControl = new google.search.SearchControl();
searchControl.addSearcher(new google.search.LocalSearch());
searchControl.addSearcher(new google.search.WebSearch());
searchControl.addSearcher(new google.search.ImageSearch());
var location = document.getElementById("searchcontrol");
searchControl.draw(location);
}
</script>
</head>
<body onload="loadSearch()">
<div id="searchcontrol">Loading ...</div>
</body>
Google Options
var localSearch = new google.search.LocalSearch();
localSearch.setCenterPoint("South Orange, NJ");
...
__________________________________________
var opt = new google.search.DrawOptions();
opt.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
...
searchControl.draw(location, opt);
__________________________________________
var siteSearch = new google.search.WebSearch();
siteSearch.setUserDefinedLabel("SHU");
siteSearch.setUserDefinedClassSuffix("siteSearch");
siteSearch.setSiteRestriction("www.shu.edu");
...
searchControl.addSearcher(localSearch);