275

I am sending an error response to my jQuery. However, I can not get the response text (in the example below this would be Gone to the beach)

The only thing jQuery says is 'error'.

See this example for details:

php

<?
    header('HTTP/1.1 500 Internal Server Error');
    print "Gone to the beach"
?>

jQuery

$.ajax({
    type:     "post",
    data:     {id: 0},
    cache:    false,
    url:      "doIt.php",
    dataType: "text",
    error: function (request, error) {
        console.log(arguments);
        alert(" Can't do because: " + error);
    },
    success: function () {
        alert(" Done ! ");
    }
});

Now my result ist:

log:

 [XMLHttpRequest readyState=4 status=500, "error", undefined]

alert:

Can't do because: error

Any ideas?

robsch
  • 9,358
  • 9
  • 63
  • 104
jantimon
  • 36,840
  • 23
  • 122
  • 185
  • The problem appears to be in your php code. Don't you need 2 linebreaks between headers and the body text? Does the `header` function handle this? – rfunduk Oct 28 '09 at 12:42
  • thenduks: PHP knows what it is doing. The issue is that because the HTTP status coming back is 500, `$.ajax()` calls the error function passed to it. – Chris Charabaruk Oct 28 '09 at 13:49

13 Answers13

352

Try:

error: function(xhr, status, error) {
  var err = eval("(" + xhr.responseText + ")");
  alert(err.Message);
}
Matt
  • 74,352
  • 26
  • 153
  • 180
Alex Bagnolini
  • 21,990
  • 3
  • 41
  • 41
  • 149
    I prefer to use JSON.parse(xhr.responseText) – Phil-R Jul 08 '13 at 20:22
  • 81
    `eval` is EVIL... http://stackoverflow.com/questions/646597/eval-is-evil-so-what-should-i-use-instead – German Latorre Aug 08 '13 at 06:55
  • 24
    Using an `eval` here doesn't make much sense. If you want to parse a JSON response, use `JSON.parse`. In the OP's case, the response isn't even JSON or JavaScript, so your `eval` is just going to cause a SyntaxError. – Mark Amery Mar 27 '14 at 15:30
  • 1
    JSON.parse needs IE8+. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse). If support for older browsers is needed, use $.parseJSON (from jQuery, http://api.jquery.com/jQuery.parseJSON/) – Julian Oct 15 '14 at 11:32
  • I don't understand this code sample, why is `eval` and the braces here?? – phil294 Oct 29 '15 at 18:41
  • 1
    doesnt change the fact that `xhr` is undefined – phil294 Feb 21 '16 at 21:47
  • 2
    in my case requested server is powered off and neither `.responseText` nor `.responseJSON` are definied – vladkras Mar 12 '17 at 07:40
  • 1
    err has "error" instead of "Message" and as others suggested JSON.parse is better. `error: function (xhr, status, error) { var err = JSON.parse(xhr.responseText); alert(err.error); }` – saquib adil Apr 12 '18 at 16:08
  • Changing ```err.Message``` to ```err.message``` works – Tony_Bielo Jul 17 '22 at 04:50
71

For me, this simply works:

error: function(xhr, status, error) {
  alert(xhr.responseText);
}
HaoQi Li
  • 11,970
  • 14
  • 58
  • 77
58

Look at the responseText property of the request parameter.

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • I have a 'parsererror' problem in IE8 but is working in IE7 for cross-origin JSONP request. But where is the responseText property? I don't see it anywhere while checking the response object during debugging. I see only readyState, status, statusText and the other methods of the $.ajax() request object. – NLV Nov 17 '11 at 10:42
  • The xhr object should have either responseText or responseXML depending on the MIME type of the response. – tvanfosson Nov 17 '11 at 13:30
  • I found the problem. In reality jquery while creating a JSONP request won't create XHR object at all. JSON-Padding is just that dynamic script references are added pointing to the URL and the json data will be wrapped with a method which gets invoked. So XHR is not used at all. – NLV Nov 17 '11 at 13:55
  • Have an issue with IE8 and cross-origin. Spent whole day today :(. http://stackoverflow.com/questions/8165557/jquery-ajax-cross-origin-using-jsonp-getting-parsererror-only-in-ie – NLV Nov 17 '11 at 13:57
  • how do you parse repsponseText into a json object? – chovy Oct 08 '12 at 06:11
27

As ultimately suggested by this other answer and it's comments on this page:

error: function(xhr, status, error) {
  var err = JSON.parse(xhr.responseText);
  alert(err.Message);
}
Community
  • 1
  • 1
Brad Parks
  • 66,836
  • 64
  • 257
  • 336
12

The best simple approach :

error: function (xhr) {
var err = JSON.parse(xhr.responseText);
alert(err.message);
}
Mazen Embaby
  • 1,255
  • 11
  • 18
8

This is what worked for me

    function showErrorMessage(xhr, status, error) {
        if (xhr.responseText != "") {

            var jsonResponseText = $.parseJSON(xhr.responseText);
            var jsonResponseStatus = '';
            var message = '';
            $.each(jsonResponseText, function(name, val) {
                if (name == "ResponseStatus") {
                    jsonResponseStatus = $.parseJSON(JSON.stringify(val));
                     $.each(jsonResponseStatus, function(name2, val2) {
                         if (name2 == "Message") {
                             message = val2;
                         }
                     });
                }
            });

            alert(message);
        }
    }
user3255682
  • 81
  • 1
  • 2
5

If you want to get Syntax Error with line number, use this

error: function(xhr, status, error) {
  alert(error);
}
Karthikeyan P
  • 1,216
  • 1
  • 20
  • 23
  • I didn't get a line number, but "alert(error)" did give me a "Not Found" when I called $.get to read a file, which was what I needed. The xhr.responseText returned a 404 page telling me the file didn't exist. – James Toomey Dec 15 '15 at 18:11
  • Hi James, if its throw the "Not Found" error that means unable to find the "Url" or "Action" method. – Karthikeyan P Dec 18 '15 at 11:37
4

This will allow you to see the whole response not just the "responseText" value

error: function(xhr, status, error) {
    var acc = []
    $.each(xhr, function(index, value) {
        acc.push(index + ': ' + value);
    });
    alert(JSON.stringify(acc));
}
Kareem
  • 5,068
  • 44
  • 38
4

you can try it too:

$(document).ajaxError(
    function (event, jqXHR, ajaxSettings, thrownError) {
        alert('[event:' + event + '], [jqXHR:' + jqXHR + '], [ajaxSettings:' + ajaxSettings + '], [thrownError:' + thrownError + '])');
    });
2

I used this, and it worked perfectly.

error: function(xhr, status, error){
     alertify.error(JSON.parse(xhr.responseText).error);
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
0

Try this to have complete error detail in console.

error: function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log("Error Thrown: " + errorThrown);
                    console.log("Text Status: " + textStatus);
                    console.log("XMLHttpRequest: " + XMLHttpRequest);
                    console.warn(XMLHttpRequest.responseText)
               }
Carn
  • 13
  • 5
-1

If you're not having a network error, and wanting to surface an error from the backend, for exmple insufficient privileges, server your response with a 200 and an error message. Then in your success handler check data.status == 'error'

chovy
  • 72,281
  • 52
  • 227
  • 295
  • 1
    Why surface with 200? 200 is OK status. He should return an error status with a custom message. – Rafael Herscovici Aug 07 '13 at 18:25
  • 1
    most apis I use actually return a 200 with an error code inside the response body. – chovy Aug 08 '13 at 08:06
  • 1
    returning something other than 200 can be problematic when you want to surface an error code or error message from the backend. non-200 is usually used to indicate that the request itself failed due to network reasons...not that the user doesn't have permission for example. In our app, we use promises in our "MakeAPICall" which looks for an error code in a 200 response and fires the `fail` method instead of the `done` method. All requests return an object that contains a 'status' object with code and message. – chovy Aug 12 '13 at 20:35
  • 1
    http://en.wikipedia.org/wiki/HTTP_403 for the permission. some more interesting read here http://stackoverflow.com/questions/7996569/can-we-create-custom-http-status-codes – Rafael Herscovici Aug 12 '13 at 20:43
  • 1
    403 is pretty basic interpretation...and you can't send a response body. My permission was just an example. There are error codes I want to surface that are app-specific. HTTP codes do not encompass all of these. – chovy Aug 12 '13 at 23:44
  • k, you didnt even bother to visit the link i gave you. so, continue as you wish, happy coding. – Rafael Herscovici Aug 13 '13 at 13:38
-1

err.responseText contain HTML tags you can get error message from these tags easily...
For example:

$(err.responseText)
// k.fn.init(12) [text, title, text, meta, text, style, text, span, text, font, text, //comment]

$.ajax({
    async: bAsync,
    type: 'POST',
    url: pUrl,
    contentType: 'application/json; charset=utf-8;',
    dataType: 'json',
    data: pData,
    success: fn,
    error: function(err) {
        alert( $($(err.responseText)[1]).text() )
        debugger;
    }
});
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • The question was related to the Ajax request where the dataType is "text", if you are talking about json datatype, the answers would be different. For json datatype, we have xhr.responseJSON object that contains the message key. – seb_dom May 29 '22 at 14:39