Show Ajax errors returned from PHP

0

I'm having trouble showing a custom error in a php response sent by ajax.

Suppose this call Ajax:

var uri = "http://localhost/aniadir.php"
        $.ajax({
            url: uri,
            data: data,
            method: "POST",
            dataType:"json",
            async: true,

            success: function (response) {

                console.log("OK" + response.data.message);



            },
            error: function (xhr, textStatus, errorMessage) {

                console.log("ERROR" + errorMessage + textStatus + xhr);

            }
        }); // end ajax

From PHP I forced an error in the connection to the DB:

$mysqli = new mysqli('localhost', 'root', 'error', 'tabla');

$jsondata["success"] = false;
$jsondata["data"] = array(
   'message' => $mysqli->error     
);

 header('Content-type: application/json; charset=utf-8');
 echo json_encode($jsondata, JSON_FORCE_OBJECT);

If the answer is success, the message is correctly displayed by response.data.message

The problem is how to display the message created in PHP when it is an error.

    
asked by Alvaro Garcia Solano 24.03.2018 в 12:56
source

1 answer

0

The point is that you are not reporting an HTTP error. For the JS, it is a request that has been answered correctly.

Yes, in the JSON you put a "success" field to false, but that's not what the JS controls. The JS looks at the HTTP Response Code; if the PHP ends normally (no exception) it will return 200 and for the JS the message will not be error.

What you have to do for JS to invoke the handler error is to return an HTTP Response Code of error, in this case the most normal would be 500 (Internal Server Error).

You can use the link function.

    
answered by 24.03.2018 в 13:08