Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);     xhr.open("POST", "/upload_image");     xhr.send(formData); } 

Any ideas? I'm testing this on Chrome.

like image 334
Ben Simmons Avatar asked Jul 21 '11 21:07

Ben Simmons


People also ask

What event is fired by XMLHttpRequest objects when they are finished loading the data from the server?

The load event is fired when an XMLHttpRequest transaction completes successfully.

What does XMLHttpRequest onload do?

The onload Property With the XMLHttpRequest object you can define a callback function to be executed when the request receives an answer.

How do I return a response from XMLHttpRequest?

The XMLHttpRequest response property returns the response's body content as an ArrayBuffer , a Blob , a Document , a JavaScript Object , or a string, depending on the value of the request's responseType property.

What is XMLHttpRequest error?

This error is a Javascript error and it can be inspected from AndroidStudio terminal or from the browser console. If you run into this problem it means that the requests to the API server are failing due to a CORS error.


1 Answers

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.

like image 94
Joe Avatar answered Sep 24 '22 06:09

Joe