Presentation is loading. Please wait.

Presentation is loading. Please wait.

AJAX – Async JavaScript and XML Bert Wachsmuth. Review Last-Last Time  Internet, IP addresses, ports, client-server, http, smtp  HTML, XHTML, XML 

Similar presentations


Presentation on theme: "AJAX – Async JavaScript and XML Bert Wachsmuth. Review Last-Last Time  Internet, IP addresses, ports, client-server, http, smtp  HTML, XHTML, XML "— Presentation transcript:

1 AJAX – Async JavaScript and XML Bert Wachsmuth

2 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

3 Homework Exercise:  Come up with a math problem that can be the basis of a JavaScript program/simulation  Enhance our “random cannon shoot” program

4 DOM – Magic Trick (1) A Magic Trick A Magic Trick

5 DOM – Magic Trick (2) A Magic Trick function magic() { var image = document.getElementById("hat"); } A Magic Trick

6 DOM – Magic Trick (3)... function magic() { var image = document.getElementById("hat"); image.setAttribute("src", "topHat.gif"); } A Magic Trick

7 DOM – Magic Trick (4) 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); }

8 Our Extended Example

9 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)

10 Switching Styles (2) File style1.css /* Using width of screen */ body { margin: 10px; width: 100%; } h1 { background-color: blue; color: yellow; }.justified { text-align: left; } File style2.css /* For small device */ body { margin: 10px auto; width: 480px; } h1 { background-color: yellow; color: blue; }.justified { text-align: right; }

11 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" />

12 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!

13 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: <input type="button" value="Switch style" onclick="switch_style()" />

14 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; }

15 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

16 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

17 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)

18 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); }

19 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); }

20 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; }

21 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 ""; }

22 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">  Of course we need to extensively test our new code

23 Testing Cookie Code Cookie name: Cookie value: <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)" />

24 Homework  Add appropriate comments, version and author info, disclaimer, copyright info, licensing info, etc. to our library of cookie- handling 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.

25 Timers and Recursion  JavaScript provides easy access to a timer via the window functions setTimeout(‘function()’, millisecs) and clearTimeout(var) function delayedAlert() { var timer = window.setTimeout("alert('Time is up')", 5000); } <body

26 Count-Down Timer (1) … Count down Count: <input type="button" value="Emergency Stop" onclick="stop_countdown()" />

27 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"); }

28 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

29 The HTML Code Falling Object Investigation Press the drop button to simulate the drop of object from a height of 10 km. The values are updated every 0.1 seconds. Time: 0 sec. Height: 10000 meter Speed: 0 meter/second

30 var timer = null; var init_height = 10000; var delta_t = 0.1; var g = 9.98; 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"); } No Air, Calculus

31 var timer = null; var init_height = 10000; var delta_t = 0.1; var g = 9.98; 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"); } No Air, Simulation

32 var timer = null; var init_height = 10000; var delta_t = 0.1; var g = 9.98; var k = 0.5;  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"); } Air resistance, simulation

33 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

34 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 weather- forecast program – why?

35 Our own XML Data File addressdata.xml Bert Wachsmuth wachsmut@shu.edu Silke von der Emde vonderemde@vassar.edu

36 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(" " + name + "(" + mail + ") "); }

37 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 names = null; // an array of all names var emails = null; // an array of all emails var recno = 0; // current record displayed var rectot = 0; // total records available function loadData() // loads data file and sets names and emails arrays function showRecord() // displays the current record function nextRecord() // increments recno and calls showRecord function prevRecord() // decrements recno and calls showRecord function findRecord() // prompts for name and searches names array

38 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/

39 Google's Search API <script src="http://www.google.com/jsapi" 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); } Loading...

40 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);


Download ppt "AJAX – Async JavaScript and XML Bert Wachsmuth. Review Last-Last Time  Internet, IP addresses, ports, client-server, http, smtp  HTML, XHTML, XML "

Similar presentations


Ads by Google