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 ?
– Diogo dgo
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).
– Guilherme Nascimento
From what I’ve seen Submit form
– Caique Romero
@Caiqueromero I already here: <button type="Submit" id="buttonSend" >Send</button>, but it was not
– Diogo dgo
Solution Take a look at this link, it can help you....
– Carlos Calisto
@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.
– Diogo dgo
Magic, good luck man :)
– Caique Romero