In-Order AJAX Handling March 10, 2012

The most common, if not definitive operation of an AJAX application is updating a specific section of a web page without reloading the entire page.

Consider the following AJAX calculator:

<input id="part1"><br>
<input id="part2"><br>
<button onclick="calc();"><br>

<div id="result"></div>

<script>
function calc(){
var a = document.getElementById('part1').value;
var b = document.getElementById('part2').value;
var xhr = xmlHTTPRequest();
xhr.open('GET', 'sum_service.php?a='+a+'&b='+b,true);
xhr.onreadystatechange=function(){
  if (xhr.readyState==4){
    document.getElementById('result').innerHTML = xhr.responseText;
  }
}
xhr.send(null);
}
</script>


The JavaScript function in the above code can be simplified with the Nano AJAX Library:
...
<script src="nano.js"></script>
<script>
function calc(){
var a = gid('part1').value;
var b = gid('part2').value;
ajxpgn('result','sum_service.php?a='+a+'&b='+b);
</script>


It's important to know that the ajxpgn function does more than just simplifying the syntax. It guarantees that the container is populated with the response that corresponds to the most recent request.

When AJAX requests are sent asynchronously, there's a high chance that the response of a later request arrives sooner than that of an earlier request, also known as a "racing condition". ajxpgn in the Nano AJAX Library prevents racing condition by cancelling all the previous in-flight requests that are related to the target container:
...
var xhr=xmlHTTPRequestObject();
if (container.xhr!=null) container.xhr.abort();
container.xhr=xhr;
...


The code takes advantage of the abort method of the XMLHttpRequest Object, which drops the asynchronous request before its response arrives. Although this does not stop the server from handling the request, the target container won't be confused by an out-of-order response.

ajxpgn uses the XMLHttpRequest object as a flag to abort previous requests. The flag is cleared when a response arrives.

Our Services

Targeted Crawlers

Crawlers for content extraction, restoration and competitive intelligence gathering.

Learn More

Gyroscope™ ERP Solutions

Fully integrated enterprise solutions for rapid and steady growth.

Learn More

E-Commerce

Self-updating websites with product catalog and payment processing.

Learn More

Featured Download

Nano AJAX Library v3.2p

Tiny JavaScript library that brings you most of the AJAX functionality

Download    Documentation
Chat Now!
First Name*:
Last Name*:
Email: optional