How do I verify registration in real time?

Asked

Viewed 465 times

5

I have a registration system that I need to check in real time if the email exists in the database.

But the same is not working, in the <div id="resposta"></div> does not display any result.

Javascript

<script language="javascript">
document.addEventListener("DOMContentLoaded", function(){

    var email = $("#email"); 
        email.blur(function() { 
            $.ajax({ 
                url: 'plano.php', 
                type: 'POST', 
                data:{"email" : email.val()}, 
                success: function(data) { 
                console.log(data); 
                data = $.parseJSON(data); 
                $("#resposta").text(data.email);
            } 
        }); 
    }); 

        });
</script>

HTML

<input type="email" name="email" required="required" placeholder="Email">
<div id="resposta"></div>

plano.php

if(isset($_POST['email'])){ 

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

    #Conecta banco de dados 
    $sql = mysqli_query($con, "SELECT email FROM conta WHERE email = '{$emailpostado}'");

    #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 usuario cadastrado com este email')); 
    else 
        echo json_encode(array('email' => 'Usuário valido.' )); 
}
  • Why instead of returning JSON you do not make a simple echo?

  • 1

    Andrei’s answer is correct, but you can take the name if you don’t want to add a id in the field: var email = $("input[name='email']");.

  • @Sam I’ll put it this way that you wrote.

  • As was put in the answer of leo and quoted by sam, in his case, there is no need to generate a JSON on the client side, nor the server side, as it is just a phrase.

2 answers

6


Why instead of returning JSON you don’t do a simple echo?

Obs event Blur fired when input loses focus

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

 <input type="text" id="email"/>
 <div id="resultados"></div>

<script type="text/javascript">

$(document).ready(function () {

    $('#email').blur(function() {
        $th = $(this);
          $.ajax({
            url: 'plano.php',
            type: 'POST',
            data: {email: $th.val()},
            beforeSend: function(){
                $("#resultados").html("Carregando...");
            },
            success: function(data){
                $("#resultados").html(data);
            },
            error: function(){
                $("#resultados").html("Ouve um erro ao enviar sua URL");
            }
         });//ajax       
    });
});

</script>

plano.php

$email = $_POST['email'];

$con = new PDO('mysql:host=localhost;dbname=NOME_DB',"USUARIO","SENHA");

    $sql = $con->prepare("SELECT email FROM conta where email='$email'");
    $sql->execute();

    $linha = $sql->fetch(PDO::FETCH_ASSOC);

    $emailBanco = $linha['email'];

    echo $emailBanco;
    echo "<br>";

    if(isset($email ) && $emailBanco === $email ){
        echo "Este email existe no banco";
    }else{
        echo "Email digitado " .$emailBanco. " Nao existe no banco "; 
    }

3

The problem is that you are trying to get the "email" id that does not exist. This line generates an error:

var email = $("#email");

You need to enter the id in your <input/>:

<input id="email" type="email" name="email" required="required" placeholder="Email">

If you want to take the value of name. You can take it like this:

var email = $("input[name='email']");

When unexpected things like this happen, you can squeeze F12 go to console and check for errors occurring.

Browser other questions tagged

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