Error Function to return Alert

Asked

Viewed 63 times

-1

I have a function that if she returns 1 appears a alert:

form was successfully sent

If you return 0, appears a alert:

error sending your form.

When I leave the form blank the expected behavior would be to display the error Alert "error while submitting your form" and not send anything in the bank, but it is happening otherwise even giving the error Alert is sending the blank form to the bank.

  <?php 

if(!empty($_FILES['uploaded_file'])){
    $username = 'root';
    $password = '';
    $connection = new PDO( 'mysql:host=localhost;dbname=nise', $username );



    $query = "INSERT INTO denuncia (descricao, imagem, id_usuario, qual_descricao,id_bloco, id_denuncia_oque) 
          VALUES (:descricao, :imagem, :id_usuario, :qual_descricao, :id_bloco, :id_denuncia_oque)";



    $statement = $connection->prepare($query);





    $path = "img_denuncia/";
    $path = $path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path))



    $valores = array();
    $valores[':descricao'] = $_POST['descricao_denuncia'];
    $valores[':imagem'] = $_FILES['uploaded_file']['name'];
    $valores[':id_usuario'] = 2;
    $valores[':qual_descricao'] = $_POST['qual_descricao'];
    $valores[':id_bloco'] = $_POST['bloco_denuncia'];
    $valores[':id_denuncia_oque'] = $_POST['id_denuncia_oque'];

    if(!isset($_POST['descricao_denuncia']) or empty($_POST['descricao_denuncia'])) {

        echo 0;

}   elseif(!isset($_POST['qual_descricao']) or empty($_POST['qual_descricao'])) {

        echo 0;

}   elseif(!isset($_POST['bloco_denuncia']) or empty($_POST['bloco_denuncia'])) {

        echo 0;

}   elseif(!isset($_POST['id_denuncia_oque']) or empty($_POST['id_denuncia_oque'])) {

        echo 0;

}   elseif($result = $statement->execute($valores)) {

        echo 1; // dados enviados com sucesso

}   else {

        echo 0; // erro ao tentar enviar dados 

}






}
?>

Function

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
            <script>
            $(document).ready(function () {
                // evento de "submit"
                $("#b_enviar").click(function (e) {
                    // parar o envio para que possamos faze-lo manualmente.
                    e.preventDefault();
                    // captura o formulário
                    var form = $('#caixa')[0];
                    // cria um FormData {Object}
                    var data = new FormData(form);
                    // processar
                    $.ajax({
                        type: "POST",
                        url: "http://localhost/nise/aluno.php", //acerte o caminho para seu script php
                        data: data,
                        processData: false, // impedir que o jQuery tranforma a "data" em querystring
                        contentType: false, // desabilitar o cabeçalho "Content-Type"
                        //cache: false, // desabilitar o "cache"
                        // manipular o sucesso da requisição
                    }).done(function(retorno){
                        console.log(retorno);
                        retorno = parseInt(retorno);  


                        if(retorno==1)
                          {
                            //alert("Formulário enviado com sucesso");
                            $("#myModalSucess").modal('show');
                             console.log(retorno);   
                          }
                           else
                          {
                            //alert("erro ao enviar formulário");
                            $("#myModalError").modal('show'); 


                          }
                    });
                });
            });
            </script>

form

 <form id="caixa" class="center-block row col-xl-6" enctype="multipart/form-data" name="formulario"  method="POST" action="aluno.php">
                <br>
                  <div class="row p-0 no-margin col-12 col-sm-12  col-md-12 col-lg-10 col-xl-12" >
                    <div class="form-group">
                      <label for="sel1">Bloco:</label>
                      <select class="form-control " name="bloco_denuncia" id="bloco" required="required" placeholder="ex: Bloco 3" >
                        <option value="" disabled selected>Ex: Computação</option>
                        <option value="1">Bloco - Computação</option>
                        <option value="2">Bloco - Mecânica</option>
                        <option value="3">Bloco - Química</option>
                        <option value="4">Bloco - Administrativo</option>
                        <option value="5">Biblioteca </option>
                        <option value="6">Ginásio </option>
                        <option value="7">Auditório</option>
                        <option value="0">Outros</option>
                      </select>
                      </div>
                  <div class="form-group">
                      <label for="sel1">O que:</label>
                      <select select="required" class="form-control" name="id_denuncia_oque" id="sel1" required="required" >
                        <option value="" disabled selected>Ex: Laboratório</option>
                        <option value="1">Sala</option>
                        <option value="2">Banheiro(Térreo)</option>
                        <option value="3">Banheiro(Superior)</option>
                        <option value="4">Laboratório</option>
                        <option value="5">Coordenação</option>
                        <option value="6">Gabinete</option>
                        <option value="7">Telecom</option>
                        <option value="8">Outros</option>

                      </select>
                      </div>

                        <div class="form-group">
                          <label for="usr">Qual:</label>
                          <input type="text" class="form-control" id="usr" name="qual_descricao" placeholder="Ex: Lab" required="required" >
                        </div>

                  </div>
                   <textarea id="noresize" class="form-control col-12 col-sm-12 mb-12 col-md-12 col-lg-10 col-xl-12 " name="descricao_denuncia" placeholder="Faça sua denúncia aqui... " rows="13" required="required" autofocus="autofocus"></textarea>

                   <br>
                   <div id="botoes" class="row p-0 no-margin col-12 col-sm-12  col-md-12 col-lg-10 col-xl-12">  
                        <div class="botao p-0 no-margin col-6 col-sm-6 mb-3 col-md-6 col-lg-2 col-xl-10">
                       <label class="file-upload btn btn-primary">
                            Escolha o arquivo... <input  type="file" name="uploaded_file"/ accept="image/*">
                        </label>  
                       <small class="form-text text-muted">As suas mensagens não serão totalmente anônimas.</small>
                        </div>
                      <div class="botao p-0 no-margin col-6 col-sm-6 mb-3 col-md-6 col-lg-10 col-xl-2 text-right ">
                           <input id="b_enviar" type="submit" class="btn btn-success" value="Enviar" name="enviar"/>
                      </div>
                  </div>
                </form>
                <br>
                <!--Fim da caixa-->

1 answer

1


You have to make a check if the input was left blank, you can do with the following styles:

Checks whether the input was sent, if not from echo 0;:

if(!isset($input)) {
   echo 0;
}

Checks whether the input was left blank, if yes, from echo 0;:

if(trim($input) == '') {
   echo 0;
}

Checks whether the input was left blank, if yes, from echo 0; (just a different way):

if(empty($input)) {
   echo 0;
}

In your code you could change that if($result = $statement->execute($valores)) and do as follows:

In this code, you have the freedom to do a different echo for each empty input, thus being able to specify to the user what it left empty.

if(!isset($_POST['descricao_denuncia']) or empty($_POST['descricao_denuncia'])) {

    echo 0;

} elseif(!isset($_POST['qual_descricao']) or empty($_POST['qual_descricao'])) {

    echo 0;

} elseif(!isset($_POST['bloco_denuncia']) or empty($_POST['bloco_denuncia'])) {

    echo 0;

} elseif(!isset($_POST['id_denuncia_oque']) or empty($_POST['id_denuncia_oque'])) {

    echo 0;

} elseif($result = $statement->execute($valores)) {

    echo 1; // dados enviados com sucesso

} else {

    echo 0; // erro ao tentar enviar dados 

}

In case you wanted to echo 0 independent of the field that has been left blank, you can do as follows:

if(!isset($_POST['descricao_denuncia']) or empty($_POST['descricao_denuncia']) or !isset($_POST['qual_descricao']) or empty($_POST['qual_descricao']) or !isset($_POST['bloco_denuncia']) or empty($_POST['bloco_denuncia']) or !isset($_POST['id_denuncia_oque']) or empty($_POST['id_denuncia_oque'])) {

    echo 0;

} elseif($result = $statement->execute($valores)) {

    echo 1; // dados enviados com sucesso

} else {

    echo 0; // erro ao tentar enviar dados 

}
  • Thanks solved my problem, but when the form is sent the fields are not cleaning, I will put the updated code, and you see if I put in the right place.

  • 1

    @Paulovictor again, it’s not a bug, you have to program it. just search how to delete inputs with jquery

  • Thank you, I thought it would be errors, I will search. Thank you

Browser other questions tagged

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