Ben Simmons Ben Simmons - 2 years ago 229
Ajax Question

XMLHttpRequest is always calling "load" event listener, even when response has error status

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);"POST", "/upload_image");

Any ideas? I'm testing this on Chrome.

Joe Joe
Answer Source

This setup should work better for your needs:

var req = new XMLHttpRequest();'POST', '/upload_image');
req.onreadystatechange = function (aEvt) {
  if (req.readyState == 4) {
     if(req.status == 200)
      alert("Error loading page\n");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download