Good Night, Guys. I'm in need of help, I'm trying to validate and then submit the form, what I basically need is: When the user enters the CPF in the form, I want to do a check in the database, if cpf is not registered, the form is sent, otherwise a message is displayed on the same page.
<form method="post" action="pesquisa.php" id="formulario">
<div class="form-group">
<label for="cpf">CPF:</label>
<input type="text" class="form-control" id="cpf" name="cpf" maxlength="14" placeholder="Digite o seu CPF" required>
</div>
<div class="form-group">
<label for="idade">Idade:</label>
<input type="text" class="form-control" id="idade" name="idade" placeholder="Digite sua Idade" required>
</div>
<div class="form-check">
<label>
<input type="radio" name="sexo" id="sexo" value="M"> <span class="label-text">Masculino </span>
</label>
<label>
<input type="radio" name="sexo" id="sexo" value="F"> <span class="label-text">Feminino </span>
</label>
</div>
<br />
<button type="submit" class="btn btn-info" id="enviar">Iniciar Pesquisa</button>
<input type="hidden" value="false" id="validado" name="validado">
</form>
Javascript looks like this:
$("#formulario").submit(function(e){
var cpf = $("#cpf").val();
if(validarCPF(cpf)){
buscarCPF(cpf);
}else{
e.preventDefault();
$("#cpf").val('');
$("#cpf").focus();
return false;
}
});
function buscarCPF(cpf){
var req;
cpf = cpf.replace(/[^\d]+/g, '');
if(window.XMLHttpRequest) {
req = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "busca.php?cpf="+cpf;
req.open("Get", url, true);
req.onreadystatechange = function() {
if(req.readyState == 1) {
document.getElementById('resultado').innerHTML = 'Buscando CPF...';
}
if(req.readyState == 4 && req.status == 200) {
var resposta = req.responseText;
if(resposta != ""){
document.getElementById('resultado').innerHTML = "<div class='alert alert-danger' role='alert'>CPF Já Cadastrado!</div>";
}
}
}
req.send(null);
}
The problem is that I do not know how to do pro submit only if no data is returned in the search, I tried to use it, but from what I've been reading the search in the database is done in an asonic way, so the form is sent, do you have to submit the form only after doing the search in the bank?