Native AJAX Programming



 When using an AJAX style of programming the old, classic approach

programming functionality must be given up. There is no form submit any
more that posts all the client state to the server and requests for a complete
new page description using HTML.
Instead of loading several pages until the functionality is done only one page
is loaded and will stay in the browser until the end of functionality. With the
Ajax model the execution of this web page is processed in 3 different phases:
Phase 1: Loading the page
During this synchronously implemented phase the client loads the "static" part
of the application. That corresponds to displaying a form or a list without any
concrete data. (We will see later that it makes a lot of sense in some scenarios
to include a first set of data into this first page loading reduce the time until
the user can use it and to achieve content recognition for search spiders.)
The code for the page is assembled and delivered to the browser. It makes no
big difference if plain HTML, generic JavaScript or JavaScript includes are
used.
The http answer of this first call can be delivered in many situations with a
hint for the client that the local browser cache can be used to store the page
for a while and therefore the server will not be asked again for this code. The
displaying of a page in this situation is very fast and efficiently because the
bytes are retrieved from the local cache and no network delays occur.
http://msdn.microsoft.com/library/en-us/dnwebgen/html/ie_introfiddler2.asp?frame=true
Phase 2: Loading data from the server using AJAX techniques
This phase is used for retrieving more information from the web server and
then combining it into the already delivered html. This can be repeated several
times while the initial page is still loaded.
That can be the current list of the emails, (Outlook Web ACCESS, GMail) or
the data changed since the last call (GMail) or additional information to a
search word (Google Suggest).
There are also non HTML/JavaScript solutions possible. Google Maps uses
variable URLs with parameters on image objects to retrieve the bitmaps that
are part of the current shown map.
The AJAX model must be considered in both loading phases. In the first
phase the necessary (JavaScript) code must be delivered. In the second phase
this code must be used to get the information from the server.
Phase 3: Interaction with the page using AJAX techniques
Web applications need a mechanism to push information back to the server.
The most known and old solution to this is the mechanism of the built-in
<form> element that allows to post back the information stored in <input>
elements to the server. The answer from the server contains a complete new
page that will be displayed.
In contrary the AJAX solution to this is to collect and transfer the pure
information that is needed by the server and to retrieve from the server some
new information that can be integrated into the already loaded page.
We will see how this can be done by using the built-in XMLHttpRequest
object. The more comfortable solution will be shown later by using a
WebService.

The XMLHttpRequest Object
There are multiple mechanisms available that can be used to call the server
without totally refreshing the current page:
An invisible <iframe> element or a frameset with an invisible frame. The
url of this element is set to a specific value containing all parameters.
A <script> element is used to include some script fragments from a
dynamic location (not a static JavaScript file). The server creates some
JavaScript and by executing the script the results of the call are embedded
into the page
The XMLHttpRequest object is used.
The AJAX Engine always uses the XMLHttpRequest approach because. It is
available in most up to date browsers and (I hope) will soon be accepted as a
standard. Have a look at
http://www.w3.org/TR/XMLHttpRequest/
There you can find a good reference too.

AJAXing the CalcFactors Example
The core algorithm of the example, the computation of the prime factors of a
number, can also be implemented quite simply on the server. A url with the
number in a parameter is requested from the server and the http answer will
return the list of factors. The JavaScript method from CalcFactorsAsync1.htm
can be converted quite easily into C# source code and can be called using a
URL like this:
http://www.mathertel.de/AjaxEngine/S01_AsyncSamples/CalcFactorsRequest.aspx?number=266712
The source code of this server processing:

<%@ Page Language="C#" Debug="true" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.Xsl" %>
<script runat="server">
private string CalcPrimeFactors(string inputText) {
string outputText = String.Empty;
UInt64 prime; // try this factor (only primes will match!)
UInt64 number; // product of the remaining factors
if ((inputText == null) || (inputText.Length == 0) || (inputText == "0"))
return("no number given.");
prime = 2; // start with 2
number = UInt64.Parse(inputText);
while ((number > 1) && (prime * prime <= number)) {
if (number % prime != 0) {
// try the next factor (slowly)
prime += 1;
} else {
// found a factor !
outputText = outputText + " " + prime;
number = number / prime;
} // if
} // while
if (number > 1) {
// the last factor (a prime) is here.
outputText = outputText + " " + number;
}
return(outputText.Trim());
} // CalcPrimeFactors
</script>
<%
Response.Clear();
string ret = CalcPrimeFactors(Request.QueryString["number"]);
Response.Write(ret);
%>

That is the simple version of the function for the computation of the prime
factors. The more complex variant of the code from CalcFactorsAsync2.htm
is not needed. Thus programming is simplified for the server-side execution
again and massive multithreading is part of http servers from the ground up.
To start such a request from the client a quite simple code is sufficient:

var xmlObj = null;
if (window.XMLHttpRequest){
// If IE7, Mozilla, Safari, etc: Use native object
xmlObj = New XMLHttpRequest()
} else if (window.ActiveXObject) {
// ...otherwise, use the ActiveX control for IE5.x and IE6
xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlObj.open("GET", "http://localhost/CalcFactors/Request.aspx?number=" + inputText,
false);
xmlObj.send();
outputText = xmlObj.responseText;

The first part retrieves one an XMLHttpRequest object through one of the
various methods. The last 3 lines establish a connection to the server transfers
the parameter and retrieves the result.
http://www.mathertel.de/AjaxEngine/S01_AsyncSamples/CalcFactorsServer1.htm
If you tried the samples using a client side calculation you may notice the
faster response for calculation a computation. It’s faster because the C# code
on the server runs a lot better then any JavaScript code on the client.
JavaScript is still interpreted and therefore slower. The response is faster in
spite of using a network transfer for computing.
Doing it asynchronous
So we can call the server. The answer of this call can, as we know, take up
some long (cpu) time and the send() method waits for the answer of the
server. During this time and with the above implementation the client does
freeze and user input events do not execute. Again we have a locking
synchronous situation.
Sending the parameters and receiving of the answer therefore must be
implemented in 2 different methods so that in the meantime the events of the
keyboard and the mouse in the browser can execute.
The XMLHttpRequest object (here used through the xmlObj variable) must be
defined in a global scope so it will be still available and not garbage collected
at the time of the transmission of the result. The result will not be available
immediately and a new function RetrievePrimeFactors is needed:

xmlObj.open("GET", "CalcFactorsRequest.aspx?number=" + inputText, true);
xmlObj.onreadystatechange = RetrievePrimeFactors;
xmlObj.send();
This function will be called when the result is present and the field for the
result will be updated:
function RetrievePrimeFactors() {
var outputText;
if ((xmlObj != null) && (xmlObj.readyState == 4)) { //COMPLETED
// The result is the whole body of the response
outputText = xmlObj.responseText;
xmlObj = null;
document.getElementById("outputField").value = outputText;
} // if
} // RetrievePrimeFactors

http://www.mathertel.de/AjaxEngine/S01_AsyncSamples/CalcFactorsServer2.htm
With this implementation we reach the kind of the Browser application that
can be called an AJAX application. No real XML is used until know but in the
end the same result is achieved.
Do we need XML?
Many web application calling themselves as AJAX applications do not use
XML for any data transfer between the client and the server.
Some use the kind of request I use up to here that is often called a REST
request. Another approach is to use a JSON (JavaScript Object Notation)
syntax for the data to be transferred and both approaches can be combined.
An indirect AJAX approach is also very well known. This approach uses
specific marked HTML regions inside a classic page and requests the server
for updates on parts of the currently loaded page. This reduced the bytes on
the network but still transfers design and data together.
My interest is in introducing the standard WebService mechanism and in a
clear separation between html code and the data of the application.

Post a Comment

You're welcome to share your ideas with us in comments.

Previous Post Next Post