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

Question:

I have a simple form, validated with javascript , and I need to send it via POST to a PHP file that will be inserted via mysql database, but when I leave the script JS in the form it doesn't send to PHP , could someone 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>

Answer:

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

Another important thing when you call event.preventDefault(); on the click of the button it will prevent the submit being performed:

event.preventDefault();

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

Parts of code were missing, such as the method that displays the error so I created one just 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>
Scroll to Top