Verificar cpf cadastrado no banco de dados com JQuery.ajax e php
Estou batendo a cabeça na parte de vericaçao de dados existente no banco, nesse caso eu estou tentando verificar se o cpf digitado apos validado existe no banco, mas não esta funcionando, não se e o erro esta no javascprit ou na pagina php, sera que alguem consegue me ajudar? Obrigado
segue as paginas:
cadastro.html
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="Classes/css/estilo.css">
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/validacao.js"></script>
<script>
</script>
<title><?php echo $acaoPagina ?></title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="index.php">Inicio</a></li>
<li><a href="especialidades.php">Especialidades</a></li>
<li><a href="cadastrarMedico.php"> Cadastrar Médico</a></li>
<li><a href="cadastrarEspecialidades.php">Cadastrar Especialidades</a></li>
</ul>
</nav>
</header>
<main>
<section>
<div class="div-25 cadastro">
<h1> <?php echo $acaoPagina ?> </h1>
<span id="resultado"></span>
<form id="formulario" name="frmcpf" action="dadosMedico.php" method="POST" onsubmit="camposMedico();">
<input type="hidden" name="id" value="<?php echo $Medico->getId_medico() ?>">
<input type="text" name="nome" placeholder="Nome" value="<?php echo $Medico->getNome() ?>">
<input type="text" name="cpf" placeholder="CPF" value="<?php echo $Medico->getCpf() ?>">
<input type="date" name="nascimento" value="<?php echo $Medico->getNascimento() ?>">
<input type="email" name="email" placeholder="E-Mail" value="<?php echo $Medico->getEmail() ?>">
<input type="text" name="telefone" placeholder="Telefone" value="<?php echo $Medico->getTelefone() ?>">
<input type="text" name="watshapp" placeholder="Watshapp" value="<?php echo $Medico->getWhatswapp() ?>">
<input type="text" name="crm" placeholder="CRM" value="<?php echo $Medico->getCrn() ?>">
<input type="text" name="salario" placeholder="Salário" value="<?php echo $Medico->getMedia_salarial() ?>">
<select name="especialidade_medico">
<?php
if($Medico->getEspecialidade_nome()&& $Medico->getId_especialidade()):
echo"<option value='{$Medico->getId_especialidade()}'>{$Medico->getEspecialidade_nome()}</option>";
else:
echo"<option>Especialidade</option>";
endif;
$selectDados->dadosEpcialidade($Esp);
?>
</select>
<input type="submit" value="<?php echo $submit ?>" onclick="camposMedico();">
</form>
</div>
</section>
</main>
<footer>
</footer>
</body>
</html>
------------------------------------------------------------------------------------------------------------------
**validacao.js**
function init() {
$("#formulario").validate({
rules: {
nome: { required: true },
cpf: { required: true, verificaCPF: true },
nascimento: { required: true, verificaIdade: true }
},
messages: {
nome: { required: "Campo Nome Obrigatório " },
cpf: { required: "Campo CPF Obrigatório" },
nascimento: { required: "Campo Nascimento Obrigatório" }
}
});
}
jQuery.validator.addMethod("verificaCPF", function (value, element) {
value = value.replace('.', '');
value = value.replace('.', '');
cpf = value.replace('-', '');
while (cpf.length < 11) cpf = "0" + cpf;
var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;
var a = [];
var b = new Number;
var c = 11;
for (i = 0; i < 11; i++) {
a = cpf.charAt(i);
if (i < 9) b += (a * --c);
}
if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11 - x }
b = 0;
c = 11;
for (y = 0; y < 10; y++) b += (a[y] * c--);
if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11 - x; }
if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg)) return false;
var verifica=false;
jQuery.ajax({
url: 'teste.php?cpf='+cpf,
async: false,
success: function(data) {
if(data == 0) verifica = true;
}});
if(!verifica) return false;
return true;
}, "Informe um CPF válido.");
jQuery.validator.addMethod("verificaIdade", function (value, element) {
var data = new Date();
value = value.split("-");
nascimento = value;
var anos = data.getFullYear() - nascimento[0];
if (nascimento[1] > data.getMonth()) {
anos -= 1;
} else if (nascimento[1] == data.getMonth()) {
if (nascimento[2] > data.getDate()) {
anos -= 1;
}
}
if (anos <= 22) {
return false;
}
return true;
},
"A idade não pode ser menor que 22 anos ");
$(document).ready(init);
* ----------------------------------------------** *
*teste.php** *
* ** *
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
#Verifica se tem um email para pesquisa
//$emailPostado = "jrcjuniorcesar@gmil.com";
if(isset($_GET['cpf'])){
#Recebe o Email Postado
$emailPostado = $_GET['cpf'];
#Conecta banco de dados
$con = mysqli_connect("localhost", "root", "", "crud");
$sql = mysqli_query($con, "SELECT * FROM medicos where cpf ='{$emailPostado}'") or print mysqli_errno($con);
#Se o retorno for maior do que zero, diz que já existe um.
$valor;
if(($sql) AND ($sql->num_rows != 0)){
while($linha= mysqli_fetch_assoc($sql)){
$valor = $sql->num_rows. "<br>";
}
}else{
$valor = 0;
}
echo $valor;
}
?>
</body>
</html>
* --------------------------*
**Banco de dados**
create database crud;
use crud;
create table especialidades(
cod int auto_increment,
especialidade varchar (45),
primary key(cod)
);
create table medicos(
id int auto_increment,
nome varchar(45),
nascimento date,
cpf varchar(11) unique key,
crm varchar(10),
email varchar(35) unique key,
telefone varchar(12),
whatsapp varchar(12),
salario double,
especialidade_medico int,
primary key(id),
foreign key(especialidade_medico) references especialidades(cod)Discussão (1)
Carregando comentários...