intermittent XMLHTTPRequest bug, and its solution

I was tearing out my hair for the last half an hour, trying to track down the reason why an undesired behaviour was happening in IE6 on one machine, but not on another (both machines were identical – XP, SP2, etc).

After I discovered the cause, I had to hit myself – it was a bug in my own programming that I’d already described to a co-worker as something to watch out for.

The symptom was that I have a certain piece of data which is requested from the server, which, in some cases, was not being retrieved. The strange thing was that there was never any error, and a refresh of the page would sometimes work.

The cause of it was the order in which the various steps of the XMLHTTPRequest process is done.

You must follow the following steps in order:

  • Create the XMLHTTPRequest object (obvious):
    var req=new HTMLHttpRequest();
  • Assign the onreadystatechange function:
    req.onreadystatechange=function(){ /* stuff */ }
  • Send the request:
    req.send(null);

Yes, that seems obvious. But if you do come across the situation where seemingly perfect code is just not retrieving the data you are looking for, then make sure that your process is in the above order.

This error will occur with higher frequency, the higher the bandwidth of the computer. The problem is that the request is being satisfied before the computer has parsed the code which handles the retrieved data.

1 Comments.

  1. I think that happened to me when I developed the auto-updating quoteboards at work. Very annoying, but I’ll have a look at my code again to fix it!

%d bloggers like this: