amandanovaes
amandanovaes

Reputation: 704

Check if ajax was aborted

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.

Upvotes: 1

Views: 1249

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123533

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

Upvotes: 2

Related Questions