View modal when sending data to a PHP database

Asked

Viewed 544 times

0

I’m trying to make sure that after the user clicks on the send 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>
<script src="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();
        }
    }
?>
  • 1

    Instead of using the direct event on the button, you can try a javascript that opens the modal under the conditions you determine... Example: $('. botao'). click(works(){ If(condition) $('modal'). modal('open'}); replacing the button and modal values by the class or id of them.

1 answer

1

So, I’ve been through this and it seems that your solution is AJAX with HTML5 validation. Your question is unclear, but I’ll take that 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: should never do the validation only in the frontend, do 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">

There you use a Jquery to detect if they have given Ubmit in your form (detail: if a required field is not filled in, the user receives an alert on 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 is already a path to be followed. Search also on google: Jquery PHP Ajax and you will have several examples from the easiest to the most complete.

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 you fill something. But of course in PHP you should also validate this ok friend? Now, we’ll take 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 kind of crude way, a modal for success and another modal for error. What will happen is that the page will reload and if there is error, will trigger the error modal, otherwise the successful.

These codes need to be improved, but that’s up to you. Good luck!

  • Didn’t work :/ no more displays on the site when I put the code without ajax... and with ajax didn’t work, continued the same error

  • Edit the answer by placing the code you used and the exact error.

Browser other questions tagged

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