...

View Full Version : Aborting XMLHttpRequests in FF



Beagle
06-21-2006, 04:32 PM
Here's the problem:

I'm making an acynchronous call using an XHR based on user behavior. If this behavior occurs in rapid succession, I want to abort the currently running request and make a new one. Example, fast-typers using a type-ahead control. Now, I've seen solutions using timeouts, but I don't want to solve this with timeouts if I can help it.

So, I have a function that aborts the request before sending a new one. The problem is that when the abort occurs readyState is set to 4, and the status property becomes unavailable, seemingly permanently. In order to work around the readyState being set to 4, before aborting, I wipe the readyStateChange handler (as discussed in the link below). But when I make a new request on the same XHR and set a new readyStateChange handler, the readyState is still 4 even though I just made a new request that won't get a response for another 5 seconds (my endpoint has a sleep in it for testing).

So I thought I'd test for status == 200 but that throws an exception, stating that status is not available. I could wrap a try-catch around it but, the readyState is 4 (completed) and the status is completely unavailable so I have no way of really figuring out what's going on if use a try-catch. I'd almost never be able to detect real errors from this errant behavior.

This is on Firefox 1.5, here is a link to quirksmode discussing this topic: http://www.quirksmode.org/blog/archives/2005/09/xmlhttp_notes_a_1.html

Here's my code:



var pipe = new XMLHttpRequest();
pipe.open("GET", "http://localhost/sleep1.php", true);

pipe.send(null);

pipe.onreadystatechange = function() {
if (pipe.readyState == 4) // *** 4 = REQUEST_COMPLETE ***
{
if (pipe.status == 200)
alert(pipe.readyState + " PIPE SAYS! " + pipe.responseText);
}
};

pipe.onreadystatechange = function() {};
pipe.abort();

// ***** pipe = new XMLHttpRequest(); **** This will make everything all better, but so costly and shouldn't be necessary!!!

pipe.open("GET", "http://localhost/sleep10.php", true);
pipe.send(null);
pipe.onreadystatechange = function() {
if (pipe.readyState == 4) // *** 4 = REQUEST_COMPLETE ***
{
if (pipe.status == 200)
alert("PIPE SAYS! " + pipe.responseText);
}
};


I would greatly appreciate links to anything discussing this topic, as well as anyone's advice, knowledge, or working solutions to the problem. Is there anything I can do short of creating a new XHR for the new request? Once you abort a request, can it be reused?

A1ien51
06-21-2006, 05:20 PM
put the send method after you set the onreadystatechange....

Eric

Beagle
06-21-2006, 05:52 PM
Done. Doesn't change a thing. All the problems I described above are happening exactly the same way.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum