0
I’m using AJAX and PHP to check in real time if the email is already registered in my BD, it shows a message in DIV #reply, whether the email already exists or not, so far so good. But if the email already exists it simply continues and accepts SUBMIT.
Register.php
<input id="email" name="email" type="text" value="" placeholder="Digite seu e-mail" required>
<div id="resposta"></div>
<script language="javascript">
var email = $("#email");
email.blur(function() {
$.ajax({
url: 'verificaEmail.php',
type: 'POST',
data:{"email" : email.val()},
success: function(data) {
console.log(data);
data = $.parseJSON(data);
$("#resposta").text(data.email);
}
});
});
</script>
verificaEmail.php
<?php
#Verifica se tem um email para pesquisa
if(isset($_POST['email'])){
#Recebe o Email Postado
$emailPostado = $_POST['email'];
#Conecta banco de dados
$con = mysqli_connect("localhost", "root", "", "academia");
$sql = mysqli_query($con, "SELECT * FROM usuarios WHERE Email = '{$emailPostado}'") or print mysql_error();
#Se o retorno for maior do que zero, diz que já existe um.
if(mysqli_num_rows($sql)>0)
echo json_encode(array('email' => 'Ja existe um usuário cadastrado com este email'));
else
echo json_encode(array('email' => 'Usuário valido.' ));
}
?>
Example, in my form, I have the field repeat the password.
<input name="senha_confirma" type="password" value="" placeholder="Confirme sua senha" required oninput="validaSenha(this)">
I am using setCustomValidity to check if the password is the same as the first "password field":
<script>
function validaSenha (input){
if (input.value != document.getElementById('txtSenha').value) {
input.setCustomValidity('As senhas não coincidem!');
} else {
input.setCustomValidity('');
}
}
</script>
This way the user cannot give SUBMIT before fixing it. Can someone help me solve my problem with the email field ?
You can hide the button if the return is true, or disable the next inputs if required.
– denis
I don’t mean JS that much, but here’s what I was thinking. You could make the ajax return a value, e.g.: if the email exists ajax returns "true", if it does not exist, it returns "false". Dai I use the 'setCustomValidity' as follows, if ajax returns true, I show ('This e-email already exists, try another'), and if ajax returns false, just proceed, in the same style as I used in the 'validateNew'. Something like this would be possible ?
– Dalton Gonzalo
I didn’t realize it goes through POST. See if this is what you need in a reply from http://stackoverflow.com/questions/22147637/getting-json-returns-true-or-false
– denis