January 21, 2002 - Monitoring XML Loading | 2 | WebReference

January 21, 2002 - Monitoring XML Loading | 2

Yehuda Shiran January 21, 2002
Monitoring XML Loading
Tips: January 2002

Yehuda Shiran, Ph.D.
Doc JavaScript

The DOMDocument's readyState property can give direct feedback on the XML loading process. It is very difficult to know exactly when the readyState property changes its value. For this very purpose, the DOMDocument object provides the onreadystatechange event handler. We incorporated this event handler in the following box to load an XML file. Type mydvd.xml in the input box and see that the readyState property goes through all four of its values. Type an incorrect name, and see state 3 missing from the list (on some systems). Observe the error message:


The HTML lines that implement this input box are the following:

URL: <INPUT TYPE="text" SIZE="60" ID="url">
<INPUT TYPE="button" VALUE="Load URL" onclick="JavaScript:load()">
<DIV ID="results" STYLE="color:red;font-weight:bold;"></DIV>
When the user clicks the Load URL button, the load() function is called:

function load() {
  xmldoc = new ActiveXObject("Msxml2.DOMDocument.3.0");
  xmldoc.onreadystatechange = checkState;
We create the DOMDocument object, xmldoc, and then assign checkState() as the onreadystatechange event handler. Then we load the URL entered by the user, url.value. From now on, every change in the readyState property will go through the function checkState() and be recorded. Here is the function checkState():

function checkState() {
  var state = xmldoc.readyState;
  results.innerHTML += "readyState = " + state + "<BR>"
  if (state == 4) {
    var err = xmldoc.parseError;
    if (err.errorCode != 0) {
      results.innerHTML += err.reason + "<BR>"
	} else {
	    results.innerHTML +="success" + "<BR>"
Notice that the main task of this function is recording the event itself:

results.innerHTML += "readyState = " + state + "<BR>"
The rest of the function deals with the highest state number, 4. It checks to see if there were errors during the XML loading or if the loading was successful.

To learn more about the four possible states, see our tip from yesterday.