I have this part of code in Controller, but when i make this action and IF works fine and the error message appears in console log.
But it looks like 'success' has status true. And it shouldn't
Try {
if ($last['date']) {
if ($last['date']->format('d-m-Y') == $par['date']) {
throw new \Exception('error', 500);
}
}
return new JsonResponse([
'success' => true,
'data' => $content,
'message' => 'success'
]);
} catch (\Exception $exception) {
return new JsonResponse([
'success' => false,
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
]);
}
JQuery
$.ajax({
type: "POST",
url: "/app/url",
data: TableData,
dataType: "json",
success: function(response){
console.log(response.message);
$('#message').html('<p class="alert alert-success">' + response.message + '</p>');
},
error: function (response) {
console.log(response.message);
$('#message').html('<p class="alert alert-danger">' + response.message + '</p>');
}
});
Your AJAX code is receiving the response as
success
every time, regardless of the JSON content, because you're always sending a200
response (which is success). To tell AJAX to process the response as an error (and go to theerror
method instead ofsuccess
method in your AJAX response handler), you need to send an error code in the response, i.e.400
, like this:So, if you're throwing your custom
Exception
s, you need to set thecode
property for each according to their real HTTP meaning.Now, the
success
anderror
handlers in AJAX have different parameters. Insuccess
, the first parameter isdata
, simply the data returned from the server. On the other hand, inerror
, the first parameter is anjqXHR
object. To access the data in this object, you have a handful of different parameters, but what you need now, since you have JSON, isjqXHR.responseJSON
. So, now your error message will be inresponse.responseJSON.message
, not inresponse.message
. See more about this here.