How to get the jQuery $.ajax error response text?

Viewed 705303

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?

13 Answers

I used this, and it worked perfectly.

error: function(xhr, status, error){
     alertify.error(JSON.parse(xhr.responseText).error);
}

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;
    }
});

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: "+MLHttpRequest);
                    console.warn(xhr.responseText)
               }
Related