How to view PHP errors using Ajax and JSON?

Asked

Viewed 431 times

1

You know those error messages that PHP returns when we write some wrong code or, for example, we call some variable that doesn’t exist, or we even try to include a non-existent 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 returned (if there is no error in the code). How then to make PHP error messages appear when using Ajax and JSON?

1 answer

1

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

  • 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.