views:

518

answers:

3

Every once and a while I get this error in IE when making an AJAX request to a handler that returns a small response of type text/plain. It seems that this error will start happening, occur a few times, and then it will stop. Very annoying.

I am using the latest jQuery library. The error throws in the complete() function when I try to access xhr.responseText. How can I prevent this from happening?

  $.ajax({
    url: "Inquire.ashx",
    data: data,
    dataType: "text",
    timeout: 5000,
    complete: function(xhr, status) {
      var resp = xhr.responseText; // ERROR!

      if(resp.substr(0, 4) == "http")
        window.open(resp, "PopWin");
      else
        showError(resp);
    }
  });
A: 

I haven't used the jQuery Ajax functionality directly, so I'm just kind of guessing here, but:

Have you tried using success instead of complete?

Have you tried other dataTypes? Based on the jQuery documentation, I wouldn't expect the text dataType to return an object, but that seems unlikely to be the problem if it's working most of the time.

Brock Boland
Thanks. The "complete" callback actually gets called after "success", so I don't think is going to help anything, but it's probably worth trying. If I use a different dataType, jQuery is going to try to process it, which I don't want because the handler returns a plain text string.
Josh Stodola
A: 

As it turns out, the error was caused because the readyState property of XmlHttpRequest was at 3, which means the request is still in process. I don't understand why jQuery fires my complete function before readyState is 4! I put this at the very top of my success callback, and have not seen the error since...

  if(xhr && xhr.readyState != 4) {
    setTimeout(arguments.callee, 50);
    return;
  }

This is a very ugly solution that I hate, but it seems to fix the problem.

Josh Stodola
+1  A: 

I know this question is over a month old, but I think I know what your problem was.

The complete() callback is executed after both success() or error() are called. In your case, I suspect your call was timing out and so if you had supplied an error callback, it would have triggered, but in this case complete() gets called with readyState at 3. Just increase your timeout and/or check for this error state.

JesDaw