I read all these similar questions: 1, 2, 3, 4, 5 and 6. But I need to debug more.
All of that questions say that problem is due to cross domain policy and e.preventDefault()
solves problem. But I doubt that this can break some other things so I need to be sure.
In my site I have an operation which is fired 15k times a day. When user visits a webpage, my javascript file checks for an element. If element exists it makes an AJAX call.
$(document).ready(function() {
// I do something here
if ($('#mydiv').length !== 0) {
var startTime = new Date().getTime();
$.ajax({
type: "POST",
url: "/mypage",
success: function (data) {
// I do something here
},
timeout: 20000,
error: function(r, s, e) {
var elapsedTime = (new Date().getTime() - startTime );
var string = "readyState: "+r.readyState+", status: "+r.status+", statusText: "+r.statusText+", responseText: "+r.responseText+", textStatus: "+s+", error: "+e +", elapsedTime: "+elapsedTime;
// send this string to server for logging
formData = {string:string};
$.ajax({
url : "/mylog",
type: "POST",
data : formData
});
}
});
}
// I do something here
});
For the 15k requests, ~70 times user gets AJAX error. ~20 is due to timeout. ~50 is due to an unknown error. When I check clients' logs I see that AJAX request gives these values for unknown error: readyState: 0, status: 0 and statusText: error
Although e.preventDefault() is recommended for this issue. I need to know what user makes for this error. In my javascript file I don't make any cross domain request. But I can't know what user made for this error ? Is it possible to know more for this error ?
Note: I track the time between "AJAX call start" and "AJAX error". Average time is 1500-2000 ms.
Edit: If I use preventDefault()
, where can I put it ? Because I don't register a click function etc.
Edit2: This page says this:
We found out that this could happen if the ajax request is getting canceled before it completes. We could reproduce the problem if we triggered the ajax request and then immediately click on a link to navigate away from the page. jQuery throws the error event when the user navigates away from the page either by refreshing, clicking a link, or changing the URL in the browser.
But I couldn't reproduce the problem by clicking some link while AJAX is loading.