I have a simple form, validated with javascript
, and I need to send via POST
to a PHP
file that will insert via mysql
database, however when I leave script JS
in form
it does not send to PHP
, could anyone 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>