1

I am not using jquery (cause I cant in this specific project) so how do I know the request was aborted by user using .abort() method? I read a lot and there is no abort method in the object XMLHttpRequest.

I know I can chek the status and readyStatus of onreadystatechange but it does not tell me anything if the connection was aborted thans.

amandanovaes
  • 694
  • 2
  • 7
  • 20
  • but I cant listen to onreadystatechange and trigger an event if readystatus is 0 cause when the user starts the connection it's 0 too. – amandanovaes Mar 21 '14 at 16:55
  • possible duplicate of [How can I tell if "abort()" has been called on an XMLHTTPRequest](http://stackoverflow.com/questions/1064196/how-can-i-tell-if-abort-has-been-called-on-an-xmlhttprequest) – Cᴏʀʏ Mar 21 '14 at 16:55
  • but there they did not find an answer. How does jquery do that? – amandanovaes Mar 21 '14 at 16:59
  • @amandanovaes As long as the request has been opened, a `readyState` of `0` should look out of place and suggest an `.abort()` as even `.open()` changes it to `1`. – Jonathan Lonowski Mar 21 '14 at 17:00
  • I am doing objeto.onreadystatechange = function() { console.log(objeto.readyState);} but it never changes to 0 when I abort. It changes to 4! – amandanovaes Mar 21 '14 at 17:04
  • jQuery works by tracking their own special state. They start it out at `0`, and modify it as the request goes along. They evaluate the result of the request for a general "success" or "error" case. If not successful, and their state is still `0`, it's considered aborted. They raise the `error/fail` event with the status. This is a very oversimplified explanation; if you want to investigate how they do it exactly, [go read the source](https://github.com/jquery/jquery/blob/master/src/ajax.js). – Cᴏʀʏ Mar 21 '14 at 17:12

1 Answers1

2

You can determine if the request has been aborted by testing the readyState, which will again be 0.

var xhr = new XMLHttpRequest();
console.log(xhr.readyState); // 0

xhr.open('GET', '/');
console.log(xhr.readyState); // 1

xhr.abort();
console.log(xhr.readyState); // 0

If you need to know when it's aborted, not just if, then you'll have to use onabort as onreadystatechange won't be triggered by it.

var xhr = new XMLHttpRequest();

xhr.onabort = function () {
    console.log('Was aborted', xhr.readyState);
};

xhr.open('GET', '/');
xhr.send();

xhr.abort(); // Was aborted 0
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • please take a look at my code http://stackoverflow.com/questions/22565513/ajax-readystate-never-returns-0-on-abort . Besides when I use onabort it says roperty 'onabort' of object # is not a function – amandanovaes Mar 21 '14 at 17:31