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:
var a = document.getElementById('part1').value;
var b = document.getElementById('part2').value;
var xhr = xmlHTTPRequest();
document.getElementById('result').innerHTML = xhr.responseText;
var a = gid('part1').value;
var b = gid('part2').value;
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:
if (container.xhr!=null) container.xhr.abort();
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.
uses the XMLHttpRequest object as a flag to abort previous requests. The flag is cleared when a response arrives.