Email verification works, but then doesn’t "update" when I type and email correctly

Asked

Viewed 30 times

-1

When I type an already registered email it displays the message saying that the email is already in use and disables the Ubmit button, but when I type the right email the message does not disappear, how to do for when the email is correct the message exit and enable it?

verificaEmail.php

    #Recebe o Email Postado
    $emailPostado = $_POST['email'];

    #Conecta banco de dados 
    include('conn.php');
    $sql = mysqli_query($conn, "SELECT * FROM cliente 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' => 'Email já cadastrado')); 
        }

}
?>
<div class="wrap-input100">
  <input class="input100" type="email" id="email" name="email" placeholder="Email" required>
  <div class="resposta" id='resposta'></div>
</div>

<button class="login100-form-btn" id="submit">Cadastrar</button>

<script>
  //Verifica email
  var email = $("#email");
  email.change(function() {
    $.ajax({
      url: 'verificaEmail.php',
      type: 'POST',
      data: {
        "email": email.val()
      },
      success: function(data) {
        console.log(data);
        data = $.parseJSON(data);
        $("#resposta").text(data.email);
        $("#submit").attr("disabled", true);

      }
    });
  });
</script>

1 answer

0


Could put a else in checking the email in PHP by returning a value in the key email, as an "ok", for example:

if(mysqli_num_rows($sql)>0) {
   echo json_encode(array('email' => 'Email já cadastrado')); 
}else{
   echo '{"email": "ok"}';
}

And in Javascript you use ternary operators to empty/fill the div and enable/disable the button according to the return:

$("#resposta").text(data.email === "ok" ? '' : data.email);
$("#submit").attr("disabled", data.email === "ok" ? false : true);

Tip

If the expected return is always a JSON, then instead of converting the return with $.parseJSON(data); you can add an option in AJAX that already does so. Just add dataType: "json", in AJAX and remove the line data = $.parseJSON(data); in the success.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.