Well, usually I do the following;
$message = array("message" => "", "error" => "");
try{
//Seu código aqui
}catch (Exception $e){
$message['message'] = "Coloque a mensagem de erro aqui";
$message['error'] = $e->getMessage();
return $message;
}
In this case, let’s imagine that this piece of code is a Return of a function. By receiving the value you give a:
json_encode($return); Exit();
On the return of the ajax function I did a general method that identifies whether it returned this json with the error != "" demonstrating that it returned the error. I do the check and send the message->error to the console.log(); or depending on the location play this for a cute alert on the screen; Not returning this it simply keeps what it would normally do.
$.ajax({
url : "cadastrar.php",
type : 'post',
dataType: "json",
data : {
nome : "Maria Fernanda",
salario :'3500'
}
})
.success(function(data){ //data = retorno json do php
if(hasError(data)){
messagemDeErroQualquer(data);
}else{
facaOQueDeveriaFazer();
}
})
function hasError(data){
if (typeof data.error !== 'undefined') {
return true;
}else
return false;
}
I tested it here and it didn’t work
– Josias Bueno
So, you make the call ajax, expect the return or error of the same to the call. Don’t forget to put "dataType" as json, otherwise it will interpret as just any text/html. If an error occurs, its function within php (within Try/catch) will force the return of an array with "message" and "error". Since there were no "errors" in the php file as it did not return an untreated Exception, it will normally enter the "Success" function of the ajax. There check if there is or not the variable "error" within "date". If you have, gave way. If not, continue your work.
– Bruno Luiz K.