Module4 Notes (AWT)
Module4 Notes (AWT)
Module -4
AJAX with XMLHTTP object : Part 2
Handling multiple XMLHttpRequest objects in the same page
AJAX Patterns
Predictive Fetch
Multi-Stage Download
Submission Throttling
Page 1
Handling multiple XMLHttpRequest objects in the same page
Using single XMLHttpRequest object
Let us consider, you are communicating with a PHP script on the server, dataresponder.php.
When you clicked button 1, a value of 1 was sent to the server, which sent that value back.
When you clicked button 2, a value of 2 was sent to the server, which sent that value back.
So far so good.
But if the user gets impatient and clicks buttons at random. The problem is that the
application uses only one XMLHttpRequest object, but now that object is being asked to send
multiple requests to the server. And depending on how fast or slow the server is, the
responses could get mixed up—the user could even click button 1, and then button 2, and
see the response from clicking button 1 if the server returned the responses out of order.
Single.html
<html>
<head>
<title>Sending Data to the Server</title>
<script language = "javascript">
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
Page 2
<body>
<h1>Sending Data to the Server</h1>
<form>
<input type = "button" value = "Fetch message 1"
onclick = "getData('dataresponder.php?data=1', 'targetDiv')">
<input type = "button" value = "Fetch message 2"
onclick = "getData('dataresponder.php?data=2', 'targetDiv')">
</form>
<div id="targetDiv">
<p>The fetched message will appear here.</p>
</div>
</body>
</html>
dataresponder.php:
<?php
if ($_GET["data"] == "1") {
echo 'The server got a value of 1';
}
if ($_GET["data"] == "2") {
echo 'The server got a value of 2';
}
?>
That out-of-order possibility comes about because the application uses only one
XMLHttpRequest object, even though the user might make multiple requests. You can see the
problem in the code, which just uses one XMLHttpRequest object.
Now, the question is, how do you handle multiple XMLHttpRequest requests at more or less
the same time? Our first solution is the obvious one—use two XMLHttpRequest objects.
Page 3
Using two XMLHttpRequest objects
Here, we create two XMLHttpRequest objects, one for each button. First, we create one
XMLHttpRequest object, XMLHttpRequest1 for button ‘fetch message1’ and second object
XMLHttpRequest2 for button ‘fetch message2’.
Example:
Double.html
<html>
<head>
<title>Using Two XMLHttpRequest Objects</title>
if (window.XMLHttpRequest)
{
XMLHttpRequestObject1 = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
XMLHttpRequestObject1 = new
ActiveXObject("Microsoft.XMLHTTP");
}
if (window.XMLHttpRequest)
{
XMLHttpRequestObject2 = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
XMLHttpRequestObject2 = new
ActiveXObject("Microsoft.XMLHTTP");
}
<body>
<h1>Using Two XMLHttpRequest Objects</h1>
<form>
<input type = "button" value = "Fetch message 1"
onclick = "getData1('dataresponder.php?data=1', 'targetDiv')">
<input type = "button" value = "Fetch message 2"
onclick = "getData2('dataresponder.php?data=2', 'targetDiv')">
</form>
<div id="targetDiv">
<p>The fetched message will appear here.</p>
</div>
</body>
</html>
dataresponder.php
<?php
if ($_GET["data"] == "1") {
echo 'The server got a value of 1';
}
if ($_GET["data"] == "2") {
echo 'The server got a value of 2';
}
?>
The below diagram is a pictorial representation of working of above program.
Page 5
Using an array of XMLHttpRequest objects
Using two XMLHttpRequest objects addressed the problem. But what if there are three
buttons in the application? should we write code for three XMLHttpRequest objects?
What if there are a hundred buttons? What if the user clicked the two buttons a dozen
times? Clearly, we need a better solution.
Here’s how that works in a new example, array.html. We can start by creating for
theXMLHttpRequest objects a new array named XMLHttpRequestObjects, using the
JavaScript Array function:
Array.html
<html>
<head>
<title>Using an Array of XMLHttpRequest Objects</title>
<script language = "javascript">
var index = 0;
index = XMLHttpRequestObjects.length - 1;
if(XMLHttpRequestObjects[index]) {
XMLHttpRequestObjects[index].open("GET", dataSource);
var obj = document.getElementById(divID);
XMLHttpRequestObjects[index].onreadystatechange = function()
{
if (XMLHttpRequestObjects[index].readyState == 4 &&
XMLHttpRequestObjects[index].status == 200) {
obj.innerHTML = XMLHttpRequestObjects[index].responseText;
}
XMLHttpRequestObjects[index].send(null);
}
}
Page 6
function getData2(dataSource, divID)
{
if (window.XMLHttpRequest) {
XMLHttpRequestObjects.push(new XMLHttpRequest());
} else if (window.ActiveXObject) {
XMLHttpRequestObjects.push(new
ActiveXObject("Microsoft.XMLHTTP"));
}
index = XMLHttpRequestObjects.length - 1;
if(XMLHttpRequestObjects[index]) {
XMLHttpRequestObjects[index].open("GET", dataSource);
var obj = document.getElementById(divID);
XMLHttpRequestObjects[index].onreadystatechange = function()
{
if (XMLHttpRequestObjects[index].readyState == 4 &&
XMLHttpRequestObjects[index].status == 200) {
obj.innerHTML = XMLHttpRequestObjects[index].responseText;
}
}
XMLHttpRequestObjects[index].send(null);
}
}
</script>
</head>
<body>
<h1>Using an Array of XMLHttpRequest Objects</h1>
<form>
<input type = "button" value = "Fetch message 1"
onclick = "getData1('dataresponder.php?data=1', 'targetDiv')">
<input type = "button" value = "Fetch message 2"
onclick = "getData2('dataresponder.php?data=2', 'targetDiv')">
</form>
<div id="targetDiv">
<p>The fetched message will appear here.</p>
</div>
</body>
</html>
Page 7
An easy way to add items to the end of an array in JavaScript is to use the push
function. We can use the push function to store new XMLHttpRequest objects in the
XMLHttpRequestObjects array.
The index in the array at which the newest XMLHttpRequest object is stored is
XMLHttpRequestObjects.length –1, and we assign that value to a variable named
index so that we can keep track of the newest XMLHttpRequest object.
AJAX Patterns
Design patterns describe programming techniques to solve common problems.
Since the mid-1990s, a lot of attention has been drawn to design patterns as a way to
cut development time.
Even though the term Ajax has been around only since early 2005, the techniques
that Ajax describes have been used since the late 1990s, giving rise to several Ajax
patterns such as hidden frame technique and asynchronous XHR calls, that solve
specific problems. These are communication patterns between the client and server
using JavaScript.
Design patterns are not standards to be followed, but merely designs of solutions that
have worked previously. It is up to the development community to generate a
“collective wisdom” around specific patterns; it’s up to the individual developer to
decide whether to implement a given pattern in his or her own application.
Page 8
Ajax provides some communication control patterns for controlling the communication
between client and server to achieve the desired behavior. Few of them are listed below
— Predictive Fetch
— Multi-Stage Download
— Periodic Refresh and Fallback patterns
— Submission Throttling
Predictive Fetch
The Predictive Fetch pattern is a relatively simple idea that can be somewhat difficult
to implement: the Ajax application guesses what the user is going to do next and
retrieves the appropriate data.
It would be wonderful to always know what the user is going to do and make sure
that the next data is readily available when needed.
In reality, however, determining future user action is just a guessing game depending
on your intentions.
As a rule of thumb, only prefetch information when you believe it’s logical to assume
that information will be requisite to completing the user’s next request.
Example: 1 Page preloading
Suppose that you are reading an online article that is separated into three pages. It is
logical to assume that if you are interested in reading the first page, you’re also
interested in reading the second and third page. So, if the first page has been loaded for
a few seconds (which can easily be determined by using a timeout), it is probably safe to
download the second page in the background. Likewise, if the second page has been
loaded for a few seconds, it is logical to assume that the reader will continue on to the
third page. As this extra data is being loaded and cached on the client, the reader
continues to read and barely even notices that the next page comes up almost
instantaneously after clicking the Next Page link.
Multi-Stage Download is an Ajax pattern wherein only the most basic functionality is
loaded into a page initially. Upon completion, the page then begins to download other
components that should appear on the page. If the user should leave the page before
all the components are downloaded, it’s of no consequence. If, however, the user
stays on the page for an extended period of time (perhaps reading an article), the
extra functionality is loaded in the background and available when the user is ready.
The major advantage here is that you, as the developer, get to decide what is
downloaded and at what point in time.
This is a fairly new Ajax pattern and has been popularized by Microsoft’s start.com.
When you first visit start.com, it is a very simple page with a search box in the
middle. Behind the scenes, however, a series of requests is being fired off to fill in
more content on the page. Within a few seconds, the page jumps to life as content
from several different locations is pulled in and displayed.
The page must work in its simplest form for browsers that don’t support Ajax
technologies. This means that all the basic functionality must work without any
additional downloads. The typical way of dealing with this problem is to provide
graceful degradation, meaning that those browsers that support Ajax technologies
will get the more extensive interface while other browsers get a simple, bare-bones
interface. This is especially important if you are expecting search engines to crawl
your site; since these bots don’t support JavaScript, they rely solely on the HTML in
the page to determine your site’s value.
Periodic Refresh
The Periodic Refresh design pattern describes the process of checking for new server
information in specific intervals. This approach, also called polling, requires the browser
to keep track of when another request to the server should take place.
This pattern is used in a variety of different ways on the Web:
ESPN uses Periodic Refresh to update its online scoreboards automatically. For
example, the NFL Scoreboard, shows up-to the-minute scores and drive charts for
every NFL game being played at the time. Using XHR objects and a little bit of Flash,
the page repeatedly updates itself with new information.
Gmail uses Periodic Refresh to notify users when new mail has been received. As you
are reading an e-mail or performing other operations, Gmail repeatedly checks the
server to see if new mail has arrived. This is done without notification unless there is
new mail, at which point the number of new e-mails received is displayed in
parentheses next to the Inbox menu item.
Page 10
XHTML Live Chat uses Periodic Refresh to implement a chat room using simple web
technologies. The chat room text is updated automatically every few seconds by
checking the server for new information. If there is a new message, the page is
updated to reflect it, thus creating a traditional chat room experience.
Fallback patterns
As a developer we know that, when to send or receive data from the server, which
assumes that everything goes according to plan on the server side: the request is
received, the necessary changes are made, and the appropriate response is sent to
the client.
But what happens if there’s an error on the server? Or worse yet, what if the request
never makes it to the server?
So, When developing Ajax applications, developer should plan ahead for these
problems and describe how your application should work if one of these occur.
Example: Cancel Pending Requests
If an error occurs on the server, meaning that a status of something other than 200
or 304 is returned, developer need to decide what to do. Chances are that if a file is
not found (404) or an internal server error occurred (302), trying again in a few
minutes isn’t going to help, since both of these require an administrator to fix the
problem. The simplest way to deal with this situation is to simply cancel all pending
requests. You can set a flag somewhere in your code that says, “don’t send any more
requests.”
This clearly has the highest impact on solutions using the Periodic Refresh pattern.
Ajax solution provides additional value to the user but is not the primary focus of the
page. If a request fails, there is no reason to alert the user; you can simply cancel any
future requests to prevent any further errors from occurring.
Submission Throttling
In a traditional web site or web application, each click makes a request back to the
server so that the server is always aware of what the client is doing. The problem with
this approach is that it has the possibility to create many requests in a short amount
of time, which not only may cause problems for the server but also may cause the
user interface to slow down as each request is being made and processed.
After the data is sent, the application typically continues to gather data until either a
server response or some user action signals to stop the data collection. Figure below
outlines this process.
When not to use Submission Throttling?
The Submission Throttling pattern should never be used for mission-critical data. If
information must be posted to the server within a specific amount of time, it’s better
to use traditional form to ensure the correct and timely delivery of the information.
Example:1 The Google Suggest feature does this brilliantly. It does not send a request after each
character is typed. Instead, it waits for a certain amount of time and sends all the text currently in the
textbox. The delay from typing to sending has been fine-tuned to the point that it does not seem like
much of a delay at all.
Example :2 Incremental Form Validation
Submission Throttling can be achieved through various user interactions. When using forms, it is
sometimes useful to upload data incrementally as the form is being filled out. The most common usage
is to validate data as the user is filling in the form instead of waiting until the end to determine any
errors. In this case, you would most likely use the onchange event handler of each form element to
determine when to upload the data.
Question Bank
1. What is the purpose of time outs in web applications? How to handle time outs in AJAX.
2. How to handle multiple and concurrent request in Ajax? Explain in an example handling two
XMLHTTPRequest objects.
3. Write an Ajax application to create and use an array of XMLHttpRequest objects.
4. Briefly explain the Ajax design patterns.
5. What is a predictive fetch? Describe any one suitable situation, where, predictive fetch can be
used or likely to be used.
6. What is submission throttling? Explain this process, with a neat diagram.
7. Define multistage download design pattern in Ajax and list its upsides and downsides.
8. Explain different ways of handling multiple XMLHttp Request objects in brief, with
examples.
Page 13