How to display PHP errors using Ajax and JSON?

1

You know those error messages that PHP returns when we write some wrong code or, for example, we call some variable that does not exist, or try to include include in a nonexistent file. When we make an Ajax request without using JSON and ask it to print the return on the console, the error message is displayed. But when we are using JSON datatype, no. It only returns what we have to return (this if there is no error in the code). How do I get PHP error messages to display when we are using Ajax and JSON?

    
asked by anonymous 08.05.2018 / 22:31

1 answer

1

Well, I usually 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. When receiving the value you give one:

  

json_encode ($ return); exit ();

In the return of the ajax function I made a general method that identifies if it returned this json with the error!="", demonstrating that it returned the error. I check and send the message-> error to console.log (); or depending on the local game that for a cute alert on the screen; Not returning this he simply keeps what he 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;
}
    
08.05.2018 / 22:42