Return PHP error for Ajax

0

I am making an insert of an input field in the database using ajax and PHP . In the code below I am returning ajax a success message if everything happens well, but how do I return a message if there is an error?

function fInserir(){

            $.ajax({
                url: "php/inserirPesquisaRealizadaBanco.php",
                type: "POST",
                dataType: "json",
                data: {pesquisa:$("#iPesquisa").val(),dia:dia,mes:mes,ano:ano},
                success:function(ret){
                    alert(ret);

                }
            });

        }
$pesquisa = $_POST["pesquisa"];
$dia = $_POST["dia"];
$mes = $_POST["mes"];
$ano = $_POST["ano"];

$conn = mysqli_connect("localhost", "root", "root", "prova");

mysqli_query($conn, "INSERT INTO tabelaProva(pesquisa, dData) VALUES ('$pesquisa','$ano-$mes-$dia')");
mysqli_close($conn);

echo json_encode("Sucesso");
    
asked by anonymous 19.04.2018 / 06:04

1 answer

2

Store the return of the mysqli_query function. It will return false in case of error, for example:

$pesquisa = $_POST["pesquisa"];
$dia = $_POST["dia"];
$mes = $_POST["mes"];
$ano = $_POST["ano"];

$conn = mysqli_connect("localhost", "root", "root", "prova");

$result = mysqli_query($conn, "INSERT INTO tabelaProva(pesquisa, dData) VALUES ('$pesquisa','$ano-$mes-$dia')");
mysqli_close($conn);

/**
 * Aqui usei um ternário (um 'if' curto):
 * Se $result for igual a 'true', retorna "Sucesso";
 * Caso contrário, retorna "Falha"
 */
echo json_encode( ($result) ? "Sucesso" : "Falha" );

But you can use the condition structure, if I find it confusing, for example:

if ($result) {
    echo json_encode("Sucesso");
} else {
    echo json_encode("Falha");
}
    
19.04.2018 / 06:11