What We Will Cover
14.1: (Re)Introducing DHTML
Learner Outcomes
At the end of the lesson the student will be able to:
- Understand what DHTML is and how it is used
- Create an iframe
|
^ top
14.1.1: What is DHTML?
- The term DHMTL stands for Dynamic HTML.
- DHMTL refers to client-side web design techniques in which the user experience is enhanced by dynamic effects.
- We have already been programming DHTML using Javascript to create rollovers, form verification, and
dynamic form element population.
- The use of DHTML allows you to create cleaner, faster, and more responsive web pages.
^ top
14.1.2: Manipulating the DOM
- The majority of DHTML effects are implemented by manipulating the DOM in some way, in response to
some user action by use of Javascript event handlers.
- Some effects we have programmed in this class that are considered DHTML include:
- Inserting Values into a Form (Section 5.1.2)
- Dynamically creating html elements (The Calender script
of Section 6)
- Rollovers (Section 8)
- Form validation (Section 9)
^ top
14.1.3: Using DHTML to Include External Content
Limitations of iframes and layers
- The major limitation to using layers or iframes for external content is that both require the
included content to be complete web pages.
- This means you could not include just a portion of a web page, but would be required to include
the entire page.
- Using Ajax for similar functionality will allow you to use as small (or big) a block of HTML
code as you
like.
- Ajax will also allow you to include simple text files as well as HTML content.
^ top
14.1.4: Summary
^ top
Activity 14.1
^ top
14.2: Introducing Ajax
Learner Outcomes
At the end of the lesson the student will be able to:
- Understand the base technologies behind Ajax
- Understand the difference betwen Synchronous and Asynchronous client-server communication
|
^ top
14.2.1: What is Ajax?
- The term Ajax stands for Asynchronous Javascript and XML.
- It is a technique (not a language) that makes use of existing web languages to create
asynchronous communication between a client and a server.
- Although originally coined by Jesse James Garrett (founder of
Adaptive Path) in 2005, the underlying technologies
of Ajax have been around much longer.
- The main technologies used in Ajax are:
- You are already familiar with the first three technologies. The use of XML can be a
very bare minimum for a simple Ajax application (explained below) or can be used for more
complex communications.
^ top
14.2.2: Who Is Using Ajax?
- The Ajax technique has gotten a lot of press recently.
- Some major players have taken advantage of the flexibilty and power of Ajax including
^ top
14.2.3: Traditional vs. Ajax UI
- You may be thinking, "Okay, so what the heck does 'Asynchronous' mean"?
- Asynchronous communication allows your webpage to communicate with the server without disrupting
the user experience by having to wait for a response back (called "Sycronous" communication).
- An example of a synchronous interaction would be when a user submits a web form and then would
have to wait for a page reload while the form data is being validated on the server.
- An asynchronous interaction of this same form would mean that the user can continue on to do
other things on the page while waiting for the server's form validation results.
- Better yet, an asynchronous application could even provide server-side verification while the
user is filling out the form, all with no page reloads at all.
Synchronous Communication
- The traditional web application model (synchronous) is based on the normal HTTP protocol interaction, that
of making a request, then waiting for the response.
- The vast majority of websites use synchronous communication because that is the way the HTTP
protocol works.
- Every time a user needs to interact with the server (submitting a web form, requesting a web
page, etc), they make a single request for information to be retrieved from the server.
- The user then must wait while the request is processed and the server sends back the requested
information.
-
The following diagram illustrates the normal synchronous communication model.

- Notice that as time progresses, every time the user requests new information from the server,
they must wait for a response before continuing.
Asynchronous Communication
- Asynchronous communication acts much in the same way as synchronous communication with the exception that
the user does not need to wait for the server to respond.
- When the user makes a request from the server, they do not need to wait for the
server to return the requested information.
- This means that the user can now communicate with the server over and over again without having
to wait for page reloads.
-
The following diagram illustrates an asynchronous communication model.

- Notice how the user activity does not have to wait for responses back from the server.
^ top
14.2.4: Summary
^ top
Activity 14.2
^ top
14.3: Building the Ajax Framework
Learner Outcomes
At the end of the lesson the student will be able to:
- Program an Ajax connection to a server
- Understand what the server can return through the Ajax connection
- Program a retrieving function to process data returned through an Ajax connection
- Show the returned data on a web page
- Program to allow for multiple Ajax scripts to run on one page
|
^ top
14.3.1: Initializing the Connection
The XMLHttpRequest Object
- The asynchronous communication that allows Ajax to work is possible through the use of the
XMLHttpRequest object, available in all of the current major browsers.
- The XMLHttpRequest object was first implemented by Microsoft as an ActiveX object, but is also
natively available to both Safari and Firefox.
- Because the XMLHttpRequest object is not yet included into any web standard, there are currently
two methods in which to use it, one for Internet Explorer and one for other browsers that support
it.
- For Internet Explorer, an ActiveX object is used:
var req = new ActiveXObject("Microsoft.XMLHTTP");
- For Mozilla and Safari, it's just a native object:
var req = new XMLHttpRequest();
- Because of this inconsistancy, we will need to test which object our visitor's browser supports.
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest(); //native
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP"); //IE/Windows ActiveX version
}
-
To make our code cleaner, it would be a good idea to put our connection script into a function.
var req;
function loadData() {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest(); //native
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP"); //IE/Windows ActiveX version
}
}
The onreadystatechange event handler
- To understand what the onreadystatechange event handler does, we first need to discuss what actually
happens when an HTTP request is made.
- When any HTTP request is made (including the normal web application model), there are five
distinct states that the request can be in before the requested data is returned to the end user.
-
Each of these states has a numerical value associated with it.
| Value |
State |
| 0 |
uninitialized - no connection is present |
| 1 |
open - a connection to the server has been initialized |
| 2 |
sent - the request has been sent to the server |
| 3 |
receiving - the server is sending back to requested information |
| 4 |
loaded - the requested information has been returned |
- The onreadystatechange event handler fires at each state of the request.
- We can specify a function to be called every time the onreadystatechange event handler fires.
- This specified function will be where we gather our returned data to be used on the web page.
- If we are going to program a function named processResults(), we would assign this function
name to the onreadystatechange event handler of our
req object.
req.onreadystatechange = processResults;
- Adding the onreadystatechange event handler specification to our connection script:
var req;
function loadData() {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest(); //native
req.onreadystatechange = processResults;
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP"); //IE/Windows ActiveX version
if (req) {
req.onreadystatechange = processResults;
}
}
}
- Note that we are double checking that the ActiveX version has a valid object before continuing.
Making the connection
- The XMLHttpRequest object has a method called open().
- This method creates our connection to the server.
- The open() method has three commonly used parameters, the first two of which are required:
| method |
required |
Although can be a variety of HTTP methods, the most common are "GET" and "POST". The
"GET" and "POST" methods act in the same way as the method attribute of a form element. |
| url |
required |
This is the url of our server-side resource we are connecting to. May be either a
relative or complete url. |
| async |
optional |
The "async" parameter specifies whether the request should be handled asynchronously or
not - "true" means that script processing carries on after the send() method (explained below),
without waiting
for a response, and "false" means that the script waits for a response before continuing script
processing. |
- If we are setting up an asynchronous connection to http://goldcoastdesign.org/ajax,
and we want to use the "GET" method, our function
call to open() would look like this:
req.open("GET", "http://goldcoastdesign.org/ajax", true);
- Adding the call to the open() function to our connection script:
var req;
function loadData() {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest(); //native
req.onreadystatechange = processResults;
req.open("GET", "http://goldcoastdesign.org/ajax", true);
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP"); //IE/Windows ActiveX version
if (req) {
req.onreadystatechange = processResults;
req.open("GET", "http://goldcoastdesign.org/ajax", true);
}
}
}
Sending the request
- Another method of the XMLHttpRequest object is the send() method.
- This method call actually sends the request to the server.
- It has a single parameter named content, but for our purposes, we will simply send in
null. The null key word is required if not sending anything.
- To send our request to the server, we would code:
req.send(null);
- Adding the call to the send() function to our connection script:
var req;
function loadData() {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest(); //native
req.onreadystatechange = processResults;
req.open("GET", "http://goldcoastdesign.org/ajax", true);
req.send(null);
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP"); //IE/Windows ActiveX version
if (req) {
req.onreadystatechange = processResults;
req.open("GET", "http://goldcoastdesign.org/ajax", true);
req.send(null);
}
}
}
Making our connection function reuseable
-
To make our new connection function reusable, we will change it so we can send in any url as a
parameter.
var req;
function loadData(url) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest(); //native
req.onreadystatechange = processResults;
req.open("GET", url, true);
req.send(null);
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP"); //IE/Windows ActiveX version
if (req) {
req.onreadystatechange = processResults;
req.open("GET", url, true);
req.send(null);
}
}
}
Calling the function
Sending query information with our request
^ top
14.3.2: The Server-side Script
- Now that we are able to establish a connection to the server, we need to have a server-side
resource to return data from.
- Although you can use Ajax to simply return plain text, it is much more powerful to have a
server-side script to return some processed information.
- The server-side resource can be anything you want, but you need to remember that you are going
to include this returned data directly into your HTML.
- It wouldn't make much sense to include HTML code that had a
<head>
or <body> right
in the middle of say, a table cell.
- Similarly, the data that you are going to return should only be text that you would normally
have in the middle of your web page:
- HTML (any size block)
- Plain text
- Normally, you would have some sort of server-side scripting language (PHP, ASP, CGI, etc) to
process your request and return data.
^ top
14.3.3: Retrieving the Response
- We will now program our processResults() function to handle the returned data from the server.
- Remember that the onreadystatechange event handler is going to call this function every time the
XMLHttpRequest state changes.
The readyState property
The status property
- We also need to check to make sure that the response from the server is valid by using the HTTP
status codes.
- You are probably already familiar with the HTTP status codes such as 404 (file not found) and
500 (internal server error)
- The
status property of the XMLHttpRequest object holds the HTTP status code generated by our request.
- The HTTP status code we want to test for is 200, which means that the data has been returned
without any problems.
- Adding our test for the HTTP status code:
function processResults() {
if (req.readyState == 4) {
if (req.status == 200) {
//do something with the returned data
}
}
}
- We should also provide a default response in case there was a problem.
function processResults() {
if (req.readyState == 4) {
if (req.status == 200) {
//do something with the returned data
} else {
alert("There was a problem retrieving
the XML data:\n" + req.statusText);
}
}
}
req.statusText holds the error message you would see normally if you received an HTTP status
error message such as "file not found" or "internal server error"
Types of data returned
^ top
14.3.4: Showing the returned data
- Now that we have made a complete, valid HTTP request and have data returned to us, we can now
do something with that data.
- What you do with the data depends entirely on what you code your script to do.
- Common techniques include populating a <div> element, dynamically populating a form
select element, or providing the user with a popup indicating that the data they just entered into
a form element is invalid.
- Remember that at this point, all that is left to do is to present the user with the new data,
which is possible by manipulating the DOM.
- We will concentrate only on displaying regular text or HTML, but you can also process XML data
at this point.
- One of the most common DOM manipulation techniques is the DOM's
innerHTML property:
var myDiv = getElementById("content_div");
myDiv.innerHTML = req.responseText;
- The
innerHTML property allows us to insert our returned data into any element of our page.
- Adding the
innerHTML to our processResults() function (assuming we have an HTML element with the
id of "content_div"):
function processResults() {
if (req.readyState == 4) {
if (req.status == 200) {
if (req.responseText) {
var myDiv = getElementById("content_div");
myDiv.innerHTML = req.responseText;
} else if (req.responseXML) {
//do something with the returned XML data
}
} else {
alert("There was a problem retrieving
the XML data:\n" + req.statusText);
}
}
}
^ top
14.3.5: Having Multiple Scripts on one Page
- You may have noticed that we are not sending any parameters to our processResults() function.
- This is a limitation when assigning the function to the
onreadystatechange event handler.
- While there are cleaner ways around this, for this discussion, we will take the simpler approach.
Changing the processResults() function to be universal
Alternative (and better) Method
- The better alternative to control multiple ajax scripts running on one page would be to use
Javascript Object-Oriented programming.
- For our purposes, we will leave that exploration up to you.
^ top
14.3.6: The Complete Framework
- Our complete framework now looks like this:
function processResults() {
if (req.readyState == 4) {
if (req.status == 200) {
if (req.responseText) {
doAction(req.responseText);
} else if (req.responseXML) {
//do something with the returned XML data
}
} else {
alert("There was a problem retrieving
the XML data:\n" + req.statusText);
}
}
}
var req;
function loadData(url) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest(); //native
req.onreadystatechange = processResults;
req.open("GET", url, true);
req.send(null);
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP"); //IE/Windows ActiveX version
if (req) {
req.onreadystatechange = processResults;
req.open("GET", url, true);
req.send(null);
}
}
}
^ top
14.3.7: Summary
^ top
Activity 14.3
^ top
14.4: Ajax in Action
Learner Outcomes
At the end of the lesson the student will be able to:
- Use the provided examples to start their Ajax explorations
|
- For the following examples, links to the required files are provided rather than showing all
of the code on this page.
- To download any of the files, simply right-click and choose "Save Link As" ("Save Target As"
for IE)
^ top
14.4.1: Retrieving Content
HTML
<form action="" method="post" name="get_content_form" onsubmit="get_content(); return false;">
<br />
<input type="text" size="25" name="param" /><br />
<input type="submit" name="param_content" value="Get Content" />
</form>
<div id="content_div"></div>
File list (Right-click to download)
ajaxbase.js
get_content.js
do_action.js
get_content.phps (Remove extra 's' from file extension)
^ top
14.4.2: Dynamic Form Selects
HTML
<form action="" method="post" name="dyn_select_form">
Region:<br />
<select name="RegionID" id="RegionID" onchange="dyn_select();">
<option label="Select" value="0">Select</option>
<option label="Silicon Valley and San Francisco Bay" value="5">
Silicon Valley and San Francisco Bay</option>
<option label="Los Angeles and San Diego" value="6">Los Angeles and San Diego</option>
<option label="Sacramento" value="7">Sacramento</option>
<option label="Other" value="12">Other</option>
<option label="New York City" value="8">New York City</option>
<option label="Rest of New York State" value="9">Rest of New York State</option>
<option label="Connecticut" value="10">Connecticut</option>
<option label="New Jersey" value="11">New Jersey</option>
</select>
<br /><br />
City:
<div id="city_select_original" style="display:inline;">
<select name="CityID">
<option value="0" />Please select a region first
</select>
</div>
<div id="city_select_new" style="display:none;"></div>
</form>
File list (Right-click to download)
ajaxbase.js
dyn_select.js
do_action.js
dyn_select.phps (Remove extra 's' from file extension)
^ top
14.4.3: Category Tree Menu
Flyers
Music Packaging
Logo Work
Miscellaneous
File list (Right-click to download)
ajaxbase.js
cat_tree.js
do_action.js
cats.phps (Remove extra 's' from file extension)
^ top
14.4.4: Image Gallery
HTML
<a href="javascript:image_viewer('32');">
<img src="images/gallery/thumbs/32.jpg" border="0" /></a>
<a href="javascript:image_viewer('33');">
<img src="images/gallery/thumbs/33.jpg" border="0" /></a>
<a href="javascript:image_viewer('34');">
<img src="images/gallery/thumbs/34.jpg" border="0" /></a>
<div style="position:relative;">
<div id="imageViewer" style="display:none;"></div>
</div>
File list (Right-click to download)
ajaxbase.js
image_viewer.js
do_action.js
image_viewer.phps (Remove extra 's' from file extension)
main.css
^ top
14.4.5: Summary
^ top
Activity 14.4
^ top
Home
| WebCT
| Announcements
| Schedule
| Room Policies
| Course Info
Help
| FAQ's
| HowTo's
| Links
Last Updated: November 27 2006 @20:12:53
|