I have a form validated with JS and need to send via PHP to BD

Asked

Viewed 566 times

3

I have a simple form, validated with javascript, and need to send via POST to an archive PHP which will insert via database mysql, but when I leave the script JS in the form he does not send to the PHP, someone could help me ?

JS

window.addEventListener("load", main);

function main(){
    var btnSend = document.querySelector("#buttonSend");
    btnSend.addEventListener("click", validar);
}

function validar(){
    event.preventDefault();

    var form = document.querySelector("#form-paciente");
    var paciente = obtemPacienteFormulario(form);
    var erros = validaPaciente(paciente);


    if(erros.length > 0){
        exibeMensagensDeErro(erros);
        return;
    }

    // limpando a parte de erros
    form.reset();
    var mensagemerro = document.querySelector("#mensagens-erro");
    mensagemerro.innerHTML = "";
}

// criando objeto paciente
function obtemPacienteFormulario(form){
    var paciente = {
        namePatient: form.namePatient.value,
        phone: form.phone.value
    };
    return paciente;
}


// validando formulario
function validaPaciente(paciente){
    var erros = [];

    if(paciente.namePatient.length == 0) erros.push("Nome do Paciente deve ser preenchido!");

    return erros;
}

PHP

<?php

function insereProduto($conexao, $namePatient){
    $queryInsert = "insert into agenda (NOMEPACIENTE) values ('{$namePatient}')";
    return mysqli_query($conexao, $queryInsert);
}

$namePatient = $_POST["namePatient"];

$conexao = mysqli_connect('localhost','root','','agendamento');

    if(insereProduto($conexao, $namePatient)){ ?>
        <p class="text-success">Paciente <?= $namePatient; ?> ,adicionado com sucesso!</p>
    <?php } else{
        $msg = mysqli_error($conexao);
    ?>
        <p class="text-danger">Paciente <?= $namePatient; ?> não foi adicionado: <?= msg ?></p>
     <?php
    }

mysqli_close($conexao);
?>

HTML:

<!-- Html -->
<form id="#form-paciente">
    <div>
        <label for="namePatient">Nome paciente</label>
        <input type="text" class"form-input" name="namePatiente" id="namePatient">
    </div>
    <button id="#buttonSend">Enviar</button>
</form>
  • @Caiqueromero I put what I’m using, the question is still confusing ?

  • Do not use "Code snippet" (Stack Snippets) unnecessarily, read: http://meta.pt.stackoverflow.com/q/2115/3635 ... Its purpose is to execute something, if it is for text markup only (organize your code in the question) do not use it, use the "code sample" (Ctrl+K).

  • From what I’ve seen Submit form

  • @Caiqueromero I already here: <button type="Submit" id="buttonSend" >Send</button>, but it was not

  • Solution Take a look at this link, it can help you....

  • @Caiqueromero I just studied the code you sent, and I realized I was wrong when I called the eventPreventDefault, without treating him, when I realized it was just to call him on parole, then my code ran, Even thanks for the help.

  • Magic, good luck man :)

Show 2 more comments

1 answer

1


You must indicate in the property action of your form the page PHP that will request the data. For the data to be sent you need to perform the submit for that page, you can do it by javascript or through elements with type="submit".

Another important thing when you call the event.preventDefault(); at the click of the button it will prevent submit be realized:

Event.preventDefault();

If this method is called, the standard action will not be triggered.

Missing parts of the code, for example the method that displays the error so I created one only to be able to demonstrate:

function validar(){
    event.preventDefault(); //Evito o submit do formulário

    var form      = document.getElementById("#form-paciente");
    var paciente  = obtemPacienteFormulario(form);
    var erros     = validaPaciente(paciente);

    if(erros.length > 0){
        exibeMensagensDeErro(erros);
        return false;
    }else{
      form.submit(); //Envio o formulário se não houver erros.
    }
    
    // limpando a parte de erros
    form.reset();
    var campoErro = document.getElementById("#mensagens-erro");
    campoErro.innerHTML = "";

}

// criando objeto paciente
function obtemPacienteFormulario(form){
    var paciente = {
        namePatient: form.namePatient.value,
        phone: form.phone.value
    };
    return paciente;
}

function exibeMensagensDeErro(erros){
  var mensagemErro = "";
  
  for(i=0;i<erros.length;i++){
    mensagemErro = mensagemErro + erros[i];
  }
  
  var campoErro = document.getElementById("#mensagens-erro");
  campoErro.innerHTML = mensagemErro;
  
}


// validando formulario
function validaPaciente(paciente){
    var erros = [];
     
     
    if(paciente.namePatient.length == 0) 
      erros.push("<li>Nome do Paciente deve ser preenchido!</li>");
      
    if(paciente.phone.length == 0) 
      erros.push("<li>Telefone do Paciente deve ser preenchido!</li>");

    return erros;
}
<form id="#form-paciente" action="">
  <div>
    <label for="namePatient">
      Nome do paciente:
    </label>
    <input type="text" class"form-input" 
          name="namePatiente" id="namePatient">
  </div>
  
  <div>
    <label for="phone">
      Telefone do paciente:
    </label>
    <input type="text" class"form-input" name="phone" id="phone">
  </div>
  
  <button type="submit" id="#buttonSend" onclick="validar();">
    Enviar
  </button>
  
  <ul id="#mensagens-erro"></ul>
</form>

Browser other questions tagged

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