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

xmlhttprequest example
xmlhttprequest post
xmlhttprequest onload
xmlhttprequest https
xmlhttprequest status
xmlhttprequest post json
xmlhttprequest download file
xmlhttprequest responsetype

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:

var req = new XMLHttpRequest();
req.open('POST', '/upload_image');
req.onreadystatechange = function (aEvt) {
  if (req.readyState == 4) {
     if(req.status == 200)
      alert(req.responseText);
     else
      alert("Error loading page\n");
  }
};
req.send(formData);

In your code error callback is never called because it is only triggered by network-level errors, it ignores HTTP return codes.

XMLHttpRequest, This will be called after the response is received xhr . onload = function The separator between the name and the value is always a colon  The line break between headers is always "\r " (doesn’t depend on OS), so we can easily split it into individual headers. The separator between the name and the value is always a colon followed by a space ": ". That’s fixed in the specification. So, if we want to get an object with name/value pairs, we need to throw in a bit JS.

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.

Ajax Design Patterns: Creating Web 2.0 Sites with Programming and , XMLHTTP"); } catch (e) {} try { return new XMLHttpRequest(); } catch(e) In practice, XMLHttpRequest Calls should almost always be asynchronous. That means  Lines 3-6 add event listeners for the various events that are sent while performing a data transfer using XMLHttpRequest. Note: You need to add the event listeners before calling open() on the request.

Expanding on @rich remer's answer, here's how you could access the status yourself:

function upload_image() {
    var form = document.getElementById('upload_image_form');
    var formData = new FormData(form);

    var xhr = new XMLHttpRequest();
    xhr.addEventListener("load", function(e) {
        if(e.currentTarget.status < 400)
            alert("Load callback - success!");
        else
            alert("Load callback - error!");
    }, false);
    xhr.addEventListener("error", function(e) {
        alert("Error callback");
    }, false);
    xhr.open("POST", "/upload_image");
    xhr.send(formData);
}

Please note accessing of the e.currentTarget.status property of the response event (e). Looks like the status is actually available via any of e.{currentTarget,target,srcElement}.status - I'm not sure which one should be used as the best practice, though.

Using XMLHttpRequest, The read-only XMLHttpRequest property responseText returns the text if the request failed or "" if the request has not yet been sent by calling send() . the value of responseText always has the current content received from  XMLHttpRequest.send() Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent. XMLHttpRequest.setRequestHeader() Sets the value of an HTTP request header. You must call setRequestHeader()after open(), but before send(). Non-standard methods XMLHttpRequest.init()

function get(url) {
return new Promise(function(succeed, fail) {
  var req = new XMLHttpRequest();
  req.open("GET", url, true);
  req.addEventListener("load", function() {
    if (req.status < 400)
      succeed(req.responseText);
    else
      fail(new Error("Request failed: " + req.statusText));
  });
  req.addEventListener("error", function() {
    fail(new Error("Network error"));
  });
  req.send(null);
 });
}

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

XMLHttpRequest.responseText, Every time createXHR() is called, it goes through and checks which capability is call to call: if the browser supports native XHR, it supports native XHR always,  The HTTP response. After a successful and completed call to the send method of the XMLHttpRequest, if the server response was well-formed XML and the Content-Type header sent by the server is understood by the user agent as an Internet media type for XML, the responseXML property of the XMLHttpRequest object will contain a DOM document object.

Professional JavaScript for Web Developers, onreadystatechange, Defines a function to be called when the readyState property changes. readyState, Holds the status of the XMLHttpRequest. 0: request not  The XMLHttpRequest Object. The XMLHttpRequest object can be used to request data from a web server. The XMLHttpRequest object is a developers dream, because you can: Update a web page without reloading the page; Request data from a server - after the page has loaded ; Receive data from a server - after the page has loaded

AJAX XMLHttpRequest Server Response, called, it can access its caller by accessing f.caller, and the next level on the call For example, s.concat(t) may always return a constant string or Math.pow may 13 xhr.send(mac); 14 } Here, the external function call to XMLHttpRequest is  If you use an asynchronous XMLHttpRequest, you receive a callback when the data has been received. This lets the browser continue to work as normal while your request is being handled. Example: send a file to the console log. This is the simplest usage of asynchronous XMLHttpRequest.

Foundations of Security Analysis and Design VII: FOSAD 2012 / 2013 , Mozilla created a wrapper to use this interface through a JavaScript object which they called XMLHttpRequest. The XMLHttpRequest object was accessible as  Pass Parameters To XMLHttpRequest Object. Ask Question Asked 7 years, 8 months ago. Active 18 days ago. Viewed 63k times 11. 3. How can I pass parameters to the

Comments
  • Nice, this works! Still curious though... why isn't the "error" callback ever invoked in my setup above?
  • I have had issues with chrome just returning ajax responses very strange. I had a get that was 200 but was never completed.
  • @simmbot The error callback is never called because it is only triggered by network-level errors, it ignores HTTP return codes.
  • A status >=400 usually indicates and error, not a success ;-)