How to get the jQuery $.ajax error response text?
When a server returns an HTTP error status like 500 Internal Server Error, jQuery's default .error() callback often feels insufficient if you only receive the string "error". You might be expecting the actual body content sent by the backend, such as "Gone to the beach", but the standard implementation simply logs the status code or the generic error string. This happens because of how $.ajax handles responses that do not match the expected data types.
The issue in your specific example stems from the dataType configuration. In your snippet, you have set:
dataType: "text"
When a server response does not match the specified data type, or when the response is empty (0 bytes), jQuery defaults to using the parserError handler rather than the standard .error() handler. Even if the response body contains text, if jQuery cannot parse it according to your declared dataType, it treats the entire request as a failure at the parsing stage.
In many scenarios, especially with simple text responses or when the server sends an error status code without proper headers indicating a specific JSON or XML structure, jQuery might not populate the responseText property within the .error() callback. The arguments array you logged shows [XMLHttpRequest readyState=4 status=500, "error", undefined]. The third element is the response text, which appears as undefined in this specific context because jQuery hasn't parsed a valid data type that matches your expectation.
To retrieve the raw response text when an error occurs, you must rely on the underlying XHR object passed into the callback. The first argument of the .error() function is the jqXHR object (an instance of XMLHttpRequest). This object contains properties like responseText, status, and responseJSON.
Here is how you can modify your code to access that data:
$.ajax({
type: "post",
data: {id: 0},
cache: false,
url: "doIt.php",
dataType: "text", // Keep this if the server returns plain text
error: function (jqXHR, textStatus, errorThrown) {
// textStatus will be "error" or "parsererror"
// errorThrown is usually a generic string like "Internal Server Error"
// Check if responseText exists and is not empty
var response = jqXHR.responseText;
console.log("Status:", jqXHR.status);
console.log("Response Text:", response);
// Only alert if there is actual content
if (response) {
alert("Can't do because: " + response);
} else {
alert("Request failed with status " + jqXHR.status);
}
},
success: function () {
alert("Done !");
}
});
The key here is accessing jqXHR.responseText. This property holds the raw string returned by the server, regardless of whether the HTTP status code indicates success or failure. However, there are important caveats to consider regarding content length and encoding.
If your PHP script prints "Gone to the beach" but does not set an appropriate Content-Length header, or if the body is empty (0 bytes), jqXHR.responseText might remain empty even though the status code is 500. Browsers often treat a response with no body as an error condition where parsing fails before the text is populated.
Furthermore, ensure that your server sends the correct MIME type. If you are expecting text but the server sends HTML or JSON without specifying it correctly, jQuery's parser might throw an exception internally, preventing the .error() callback from receiving the parsed data. In modern web development, relying on raw responseText for error messages is often less secure than returning a structured response like JSON with specific error codes and descriptive messages. This allows your frontend to handle different types of failures gracefully without relying on string parsing.
If you are building a backend using Laravel, consider leveraging the framework's built-in error handling capabilities. When returning a 500 status in Laravel, it is best practice to return a JSON response with an error key containing the message, rather than echoing raw text strings directly. This ensures that your .error() handler receives consistent data structures.
// Inside your doIt.php or controller route
return response()->json(['message' => 'Gone to the beach'], 500);
By returning a structured JSON payload, you ensure that jqXHR.responseText will contain valid JSON text even on failure, and jQuery can optionally parse it if you adjust your dataType. If you must stick to raw text for legacy reasons, always verify that the server sends the full body content in the response headers to avoid empty string issues.
