I'm using FormData to ajax a file upload. The upload works, but the problem is that the "error" callback is never invoked. Even when my HTTP response is a 500 internal server error (to test this I tweak server to respond with 500), the "load" callback is invoked.
function upload_image() {
var form = document.getElementById('upload_image_form');
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function(e) {
alert("Success callback");
}, false);
xhr.addEventListener("error", function(e) {
alert("Error callback");
}, false);
xhr.open("POST", "/upload_image");
xhr.send(formData);
}
Any ideas? I'm testing this on Chrome.
This setup should work better for your needs:
In your code error callback is never called because it is only triggered by network-level errors, it ignores HTTP return codes.
code from EJS by the example code it is clear that network error has no response, it trigger error event. response trigger load event and you have to decide what to do with the response status
The load event is called whenever the server responds with a message. The semantics of the response don't matter; what's important is that the server responded (in this case with a 500 status). If you wish to apply error semantics to the event, you have to process the status yourself.
Expanding on @rich remer's answer, here's how you could access the status yourself:
Please note accessing of the
e.currentTarget.status
property of the response event (e
). Looks like the status is actually available via any ofe.{currentTarget,target,srcElement}.status
- I'm not sure which one should be used as the best practice, though.