Return PHP Error to Ajax

Asked

Viewed 577 times

0

I’m making a Insert field input in the database using ajax and PHP. In the code below I am returning to the ajax a success message if all goes 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");

1 answer

2


Store the function return mysqli_query. She 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");
}
  • I tested it here and it worked exactly as I wanted. Thanks for the help friend!

Browser other questions tagged

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