I was testing a tool that fires some asynchronous ajax requests. The response of one request can abort another one. This works great as far as I have tested this (Chrome, Firefox) but Edge doesn't like aborting! As soon as the XmlHttpRequest is blocked, Edge throws a fail - which I wish not to happen.
This is the code (that gets aborted by another snippet):
xhr = $.ajax("my-url.php")
.done(function(json) {
var data = $.parseJSON(json);
if (data.data) {
// Yay data!
} else {
// Ahw no data or empty data
}
})
.fail(function(jqXHR, textStatus, error) {
// This is triggered by Edge, `error` is "abort"
var string = "An error occurred: " + error + ".";
alert(string);
})
.always(function() {
done = true;
});
So, the result is an alert An error occurred: abort. Question one: why is Edge doing this? Does it handle XHR in a different way than other browsers? What is the standard? Secondly, how do I make sure I do not show this message? Can I simply do something like this in fail()
, or isn't that a pretty way of going about this:
if (error != 'abort') {
// Do stuff, only when error isn't abort
}
It seems that I found what happens.
This is my code (copied from yours):
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
'use strict';
var xhr, done;
function getResp() {
if (!done && xhr && xhr.readyState !== 4)
xhr.abort();
done = false;
xhr = $.ajax("json.php",{method:'GET'})
// you didn't include method so method is 'GET'
// when I change it to 'POST' Edge honors xhr.abort()
.done(function (json) {
console.log(json);
var data = $.parseJSON(json);
if (data.data) {
// Yay data!
} else {
// Ahw no data or empty data
}
})
.fail(function (jqXHR, textStatus, error) {
// This is triggered by Edge, `error` is "abort"
var string = "An error occurred: " + error + ".";
//alert(string);
console.log(string);
})
.always(function () {
done = true;
});
}
</script>
</head>
<body>
<input type="button" onclick="getResp()" value="run" />
</body>
</html>
and my php:
<?php
usleep(10000000); //10 seconds
echo '{"name":"test","qty":10,"curr":"'.date('h:i:s').'"}';
?>
General answer: Edge caches xhr GET
response and returns data immediately. FF sends request to the server. It makes all difference.
POST
requests aren't cached and xhr.abort()
produces expected result in all browsers.
Is it acceptable answer?