Modal display when sending data to the bank with PHP

0

I'm trying to make, after the user clicks the submit button, the system displays a modal with some data. But I'm not getting why even without filling anything in the form, when clicking the button, the modal is displayed:

FORM

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<form role="form" action="" method="post" enctype="multipart/form-data">
  <div class="row cadastro">
    <div class="col-md-6">
      <div class="form-group">
        <label>Nome:</label>
        <input type="text" name="nome" class="form-control" id="nome" style="color:black;border-color:black" placeholder="Digite seu nome" required="">
      </div>
    </div>
    <div class="col-md-6">
      <label>E-mail:</label>
      <div class="form-group">
        <input type="email" name="email" class="form-control" id="email" style="color:black;border-color:black" placeholder="Digite seu email" required="">
      </div>
    </div>
    <div class="col-lg-4">
      <label>genero:</label>
      <select class="select" name="genero" id="genero">
            <option disabled="" selected="" value="Outro">Selecione uma opção</option>
            <option value="Masculino">Masculino</option>
            <option value="Feminino">Feminino</option>
            <option value="Outro">Outro</option>
        </select>
    </div>
    <div class="col-lg-8">
      <label>localidade</label>
      <select class="select" name="localidade" id="localidade">
            <option value="Não informado" disabled="" selected="">Selecione uma opção</option>
            <option value="Centro">Centro</option>
            <option value="Banguê">Banguê</option>
            <option value="Tucum">Tucum</option>
        </select>
    </div>
    <div class="col-lg-6">
      <label>idade:</label>
      <input type="number" name="idade" class="form-control" style="color:black;border-color:black" onkeypress="return event.charCode >= 48" min="1" max="120" name="">
    </div>
  </div>
  <button class="btn btn-common" name="cadDados" type="submit" data-toggle="modal" data-target="#exampleModal">Enviar Dados</button>
</form>

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

PHP CODE

<?php
    if (isset($_POST['cadDados'])) {

        $nome = trim(strip_tags($_POST['nome']));
        $email = trim(strip_tags($_POST['email']));
        $genero = trim(strip_tags($_POST['genero']));
        $localidade = trim(strip_tags($_POST['localidade']));
        $doenca = trim(strip_tags($_POST['doenca']));
        $idade = trim(strip_tags($_POST['idade']));
        $insert = "INSERT INTO tb_grafico (nome,email,genero,localidade,tipo_doenca,idade) VALUES (:nome,:email,:genero,:localidade,:doenca,:idade)";

        try{
            //Proteção contra SQLINJECT
            $result = $con->prepare($insert);
            $result->bindParam(':nome',$nome,PDO::PARAM_STR);
            $result->bindParam(':email',$email,PDO::PARAM_STR);
            $result->bindParam(':genero',$genero,PDO::PARAM_INT);
            $result->bindParam(':localidade',$localidade,PDO::PARAM_STR);
            $result->bindParam(':doenca',$doenca,PDO::PARAM_STR);
            $result->bindParam(':idade',$idade,PDO::PARAM_STR);
            $result->execute();
            $contar = $result->rowCount();
            if ($contar>0) {
                echo "<div class ='alert alert-sucess' role='alert'><strong>Cadastrado com sucesso!</strong></div>";
            }
        }catch(PDOException $e){
            echo "<strong>Erro de sql: </strong>".$e->getMessage();
        }
    }
?>
    
asked by anonymous 10.03.2018 / 00:12

1 answer

1

So I've been through this and it looks like your solution is AJAX with HTML5 validation. Your question was not clear, but I take it as a yes. First, you change your button to not launch the modal:

<button class="btn btn-common" name="cadDados" type="submit">Enviar Dados</button>

Now, the fields you want to be validated you add a required:

<select class="select" name="genero" id="genero" required>

Attention: you should never validate only in the frontend, also in the backend.

Add an id to your form (in this case, "my_form"):

<form role="form" action="" id="my_form" method="post" enctype="multipart/form-data">

Then you use a Jquery to detect if they have submitted on your form (detail: if a required field is not filled, the user receives an alert at the time):

$('#my_form').submit(function(event){
    event.preventDefault();//Impede envio
    event.stopPropagation();//Impede envio

    //Pega as informações do formulário
    var frm = $("#my_form");
    var data = {};
    $.each(this, function(i, v){
        var input = $(v);
        data[input.attr("name")] = input.val();
        delete data["undefined"];
    });
    $.ajax({
        contentType:"application/json; charset=utf-8",
        type:frm.attr("method"),
        url:frm.attr("action"),
        dataType:'json',
        data:JSON.stringify(data),
        success:function(data) {
            //Aqui você pode fazer um código para saber se deu tudo certo ou ocorreu um erro no backend
            $('#MEU_MODAL').modal('show');//Mostra o modal
        }
    });
}

I know the answer was long, the code has not been tested, but it's already a way to go. Also search google: Jquery PHP Ajax and you will have several examples from the easiest to the most complete ones.

Doing without ajax:

First, you change your button to not launch the modal:

<button class="btn btn-common" name="cadDados" type="submit">Enviar Dados</button>

Now, the fields you want to be validated you add a required:

<select class="select" name="genero" id="genero" required>

Okay, with this the form only sends if they fill something. But of course in PHP you should also validate this ok friend? Now, we'll get the PHP code and put it on the same form page, put this code:

<?php
    if (isset($_POST['cadDados'])) {

        $nome = trim(strip_tags($_POST['nome']));
        $email = trim(strip_tags($_POST['email']));
        $genero = trim(strip_tags($_POST['genero']));
        $localidade = trim(strip_tags($_POST['localidade']));
        $doenca = trim(strip_tags($_POST['doenca']));
        $idade = trim(strip_tags($_POST['idade']));
        $insert = "INSERT INTO tb_grafico (nome,email,genero,localidade,tipo_doenca,idade) VALUES (:nome,:email,:genero,:localidade,:doenca,:idade)";

        try{
            //Proteção contra SQLINJECT
            $result = $con->prepare($insert);
            $result->bindParam(':nome',$nome,PDO::PARAM_STR);
            $result->bindParam(':email',$email,PDO::PARAM_STR);
            $result->bindParam(':genero',$genero,PDO::PARAM_INT);
            $result->bindParam(':localidade',$localidade,PDO::PARAM_STR);
            $result->bindParam(':doenca',$doenca,PDO::PARAM_STR);
            $result->bindParam(':idade',$idade,PDO::PARAM_STR);
            $result->execute();
            $contar = $result->rowCount();
            if ($contar>0) {
                $('#MEU_MODAL_SUCESSO').modal('show');
            }
        }catch(PDOException $e){
            $('#MEU_MODAL_DE_ERRO').modal('show');
        }
    }
?>

I did it in a rough way, one modal for success and another modal for error. What will happen is that the page will reload and if there is an error, it will trigger the modal error, otherwise the success.

These codes need to be improved, but there it is with you. Good luck!

    
10.03.2018 / 12:10