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

Slides:



Advertisements
Similar presentations
Cookies, Sessions. Server Side Includes You can insert the content of one file into another file before the server executes it, with the require() function.
Advertisements

JavaScript and AJAX Jonathan Foss University of Warwick
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
Cascading Style Sheets
Today CSS HTML A project.
Web Pages and Style Sheets Bert Wachsmuth. HTML versus XHTML XHTML is a stricter version of HTML: HTML + stricter rules = XHTML. XHTML Rule violations:
JavaScript Forms Form Validation Cookies. What JavaScript can do  Control document appearance and content  Control the browser  Interact with user.
JavaScript Forms Form Validation Cookies CGI Programs.
Web Site Design Bert Wachsmuth. Checking Homework Visit our homepage ~wachsmut/  Check the bold sites  Visit my “demo” site.
Cascading Style Sheets Controlling the Display Of Web Content.
Tutorial 10 Programming with JavaScript
Dynamic Web Pages Bert Wachsmuth. Review  Internet, IP addresses, ports, client-server, http, smtp  HTML, XHTML, XML  Style Sheets, external, internal,
AJAX (Async JavaScript and XML) and Java Applets Bert Wachsmuth.
2012 •••••••••••••••••••••••••••••••••• Summer WorkShop Mostafa Badr
Computer Concepts 2014 Chapter 7 The Web and .
Headings, Paragraphs, Formatting, Links, Head, CSS, Images
JavaScript: Control Structures September 27, 2005 Slides modified from Internet & World Wide Web: How to Program (3rd) edition. By Deitel, Deitel,
Introduction to Programming the WWW I CMSC Summer 2003 Lecture 12.
UNIT 3 DYNAMIC WEBSITES WITH CSS AND JAVASCRIPT. OBJECTIVES  CO4 Apply style to a website using CSS.  CO5 Describe the use of scripting when creating.
© Ms. Masihi.  The Dreamweaver Welcome Screen first opens when you start Dreamweaver.  This screen gives you quick access to previously opened files,
XP New Perspectives on XML, 2 nd Edition Tutorial 10 1 WORKING WITH THE DOCUMENT OBJECT MODEL TUTORIAL 10.
XP New Perspectives on Browser and Basics Tutorial 1 1 Browser and Basics Tutorial 1.
JavaScript, Fourth Edition
SYST Web Technologies SYST Web Technologies Lesson 6 – Intro to JavaScript.
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
CISC474 - JavaScript 03/02/2011. Some Background… Great JavaScript Guides: –
Web Programming: Client/Server Applications Server sends the web pages to the client. –built into Visual Studio for development purposes Client displays.
Week 9 PHP Cookies and Session Introduction to JavaScript.
CSE 154 LECTURE 12: COOKIES. Including files: include include("filename"); PHP include("header.html"); include("shared-code.php"); PHP inserts the entire.
SEG3210 DHTML Tutorial. DHTML DHTML is a combination of technologies used to create dynamic and interactive Web sites. –HTML - For creating text and image.
XP Dreamweaver 8.0 Tutorial 3 1 Adding Text and Formatting Text with CSS Styles.
 This presentation introduces the following: › 3 types of CSS › CSS syntax › CSS comments › CSS and color › The box model.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
What is Java Script? An extension to HTML. An extension to HTML. Allows authors to incorporate some functionality in their web pages. (without using CGI.
Chapter 8 Cookies And Security JavaScript, Third Edition.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Tutorial 10 Programming with JavaScript. XP Objectives Learn the history of JavaScript Create a script element Understand basic JavaScript syntax Write.
Tutorial 10 Programming with JavaScript
Using Client-Side Scripts to Enhance Web Applications 1.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Introduction to JavaScript 41 Introduction to Programming the WWW I CMSC Winter 2004 Lecture 17.
Regular Expression (continue) and Cookies. Quick Review What letter values would be included for the following variable, which will be used for validation.
Cookies Web Browser and Server use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website it is required to maintain.
Introduction to Client-Side Web Development Introduction to Client-Side programming using JavaScript JavaScript; application examples 10 th February 2005.
Use CSS to Implement a Reusable Design Selecting a Dreamweaver CSS Starter Layout is the easiest way to create a page with a CSS layout You can access.
Cookies and Sessions IDIA 618 Fall 2014 Bridget M. Blodgett.
Overview of Form and Javascript fundamentals. Brief matching exercise 1. This is the software that allows a user to access and view HTML documents 2.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Web Development 101 Presented by John Valance
JQuery Introduction © Copyright 2014, Fred McClurg All Rights Reserved.
HTML GUIDE Press F5 and then Click on the links on the left to get to the section you want Section 1: Getting Started Section 2: Moving Banner Section.
LEARN THE QUICK AND EASY WAY! VISUAL QUICKSTART GUIDE HTML and CSS 8th Edition Chapter 8: Working with Style Sheets.
Tutorial 3 Adding and Formatting Text with CSS Styles.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
(Some from Chapter 11.9 – “Web” 4 th edition and
Web Technologies Beginning Cascading Style Sheets (CSS) 1Copyright © Texas Education Agency, All rights reserved.
IS2802 Introduction to Multimedia Applications for Business Lecture 8: JavaScript and Cookies Rob Gleasure
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
JavaScript and AJAX 2nd Edition Tutorial 1 Programming with JavaScript.
PHP: Further Skills 02 By Trevor Adams. Topics covered Persistence What is it? Why do we need it? Basic Persistence Hidden form fields Query strings Cookies.
COMP 143 Web Development with Adobe Dreamweaver CC.
4.01 Cascading Style Sheets
Introduction to Web programming
Cookies and JavaScript
WEB PROGRAMMING JavaScript.
4.01 Cascading Style Sheets
Web Programming and Design
Presentation transcript:

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) A Magic Trick A Magic Trick

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

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

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

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 /* 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; }

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

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

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

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.

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

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

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 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: meter Speed: 0 meter/second

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

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

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

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:  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?

Our own XML Data File addressdata.xml Bert Wachsmuth Silke von der Emde

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

Better Use  Library to load XML data across browsers:  Use index variable to track current address and functions as follows: var names = null; // an array of all names var s = null; // an array of all s var recno = 0; // current record displayed var rectot = 0; // total records available function loadData() // loads data file and sets names and s 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

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:  or for even more information, check:

Google's Search API <script src=" 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...

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(" searchControl.addSearcher(localSearch);