How to check if the email is registered when typing on the form? [duplicate]

2

I have a registration form, and I would like you to let me know as soon as the email is entered, if it is already in the database.

I thought of using a JavaScript function with a PHP code inside that will search if there is email in the Bank, but I'm not sure if it's possible to use PHP inside JavaScript, someone has that information and otherwise it's possible to use just JavaScript for it?

    
asked by anonymous 16.11.2017 / 21:51

3 answers

8

Is it possible to do only with JavaScript?

You can not do this with JavaScript, as you require access to the database to verify that the record exists. That is, some language should be run on the server side - nothing prevents JavaScript, such as NodeJS, but it would be in a different context.

Is it possible to use PHP within JavaScript?

No. This is one of the most basic concepts on the web and many people do not understand it correctly. PHP will run on the server side and JavaScript on the client side. The only way they both communicate is through messages. The format of the message may vary according to the protocol used, but the most common is HTTP. If you need to send a JavaScript value to PHP, you need to send an HTTP request to the server. If you want PHP to return some value for JavaScript, you need to send it through the HTTP response that will be generated on the server.

I describe a little of this context here: How to write values to the MySQL database using PHP?

p>

Then how to proceed?

You should work on both fronts: JavaScript and PHP. Like JavaScript, you should:

  • Monitor the value of the email field in HTML checking for changes in value;
  • Verify that the typed e-mail is valid before making the request to the server;
    • If you make the request without validating the email, you will be demanding unnecessary network resources;
  • When the email is valid, make a GET request to the server;
    • The GET request is important to maintain application semantics: you want to get a server state from base values;
  • If the request succeeds, check the response body;
  • If the request fails, you should inform that if the email already exists, the registration will fail - or not allow the person to register at this time, as the server may be in trouble;

    So, in the code, we can have something similar to:

    const email = document.getElementById("emailInput");
    const button = document.getElementById("registerButton");
    const messages = document.getElementById("messages");
    
    function validate(email) {
      // Implemente a função de validar e-mail aqui
      return true;
    }
          
    email.addEventListener("input", function (event) {
      if (this.validity.valid || validate(this.value)) {
        fetch('verifica.php?email=${this.value}')
          .then(response => {
            if (response.ok) {
              return response.json();
            }
            throw new Error("Oops! Algo de errado não está certo...");
          })
          .then(json => {
            if (json.exists) {
              messages.innerHTML += 'E-mail já está cadastrado. Por favor, tente outro.';
            } else {
              messages.innerHTML += 'E-mail disponível.';
              button.disabled = false;
            }
          })
          .catch(error => {
            messages.innerHTML += 'Falha no servidor, por favor, tente novamente mais tarde.';
          });
      }
    });
    <form action="cadastrar.php" method="POST">
      <input id="emailInput" type="email" name="email" placeholder="Entre com o seu e-mail" required>
      <button id="registerButton" type="submit" disabled>Cadastrar</button>
      <div id="messages"></div>
    </form>

    Code Considerations:

  • I did not implement the function of validating email so as not to extend the code a lot and because it is easily found on the web;
  • I also used email.validity to compose the verification;
  • I used the input event because it is theoretically triggered for any input event that can modify the value of the field, either via mouse, keyboard or touch; for more accurate behavior of the application, it is important that you manually set all desired events, as browsers still do not follow the W3C or WHATWG specification in this regard;
  • To make the request, I used the fetch API; is experimental and the future substitute for XMLHttpRequest , but works fine using polyfill ;
  • Start the application with the button disabled and only enable it when the e-mail is verified and available. This prevents the user from making unnecessary server requests with invalid or existing e-mail, increasing application performance and improving usability;
  • If the verification request fails for any reason, I leave the button disabled to prevent the user from registering, as I assume that if an error occurred with the verification, it will also occur with the registration, then prevent the user from this embarrassing situation;
  • Now, on the server side, with PHP, you should:

  • Verify that the current request is a GET request;
  • Verify that the email value has been correctly entered;
  • Connecting to the database;
  • Check for email in the database table;
  • Produce the response to be sent to the client (browser);
  • Send the response effectively;
  • The code would look something like:

    <?php
    
    header('Content-Type: application/json');
    
    try {
        if ($_SERVER['REQUEST_METHOD'] != 'GET') {
            throw new Exception("Não é uma requisição GET");
        }
    
        $email = filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL);
    
        if (!$email) {
            throw new Exception("O e-mail informado não é um e-mail válido");
        }
    
        $mysqli = require("db.php");
        $stmt = $mysqli->prepare("SELECT EXISTS(SELECT 1 FROM emails WHERE email = ?) as 'exists'");
        $stmt->bindParam(1, $email); 
        $stmt->execute();
        $stmt->bind_result($row);
    
        if ($stmt->fetch()) {
            http_response_code(200);
            $output = $row;
        }
    } catch (Exception $e) {
        http_response_code(500);
        $output = ['error' => $e->getMessage()];
    } finally {
        echo json_encode($output);
    }
    

    So, if all goes well, PHP will return a JSON response in the format below, with a value of 0 if the email is not registered or 1, otherwise with the status code of response 200:

    {exists: 0}
    

    However, if an error occurs in the process, the response will have code 500 and a body reporting the error message:

    {error: 'O e-mail informado não é um e-mail válido'}
    
        
    17.11.2017 / 13:49
    5

    Yes, it is only possible with JavaScript through Ajax (without loading jQuery).

    HTML:

    Enter a oninput in the field where the e-mail will be typed by calling the function that will send the e-mail to the PHP file:

    <input type="email" oninput="checaEmail(this.value)" />
    

    JavaScript:

    Create two functions, one to do Ajax and the other to check if the email you typed is valid. Once the email is valid, as you type, Ajax will enter into action sent a request to the file verifica.php (you can use the filename you want, just change in the code below):

    // cria a requisição XMLHttpRequest()
    var http = false;
    if(navigator.appName == "Microsoft Internet Explorer") {
        http = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        http = new XMLHttpRequest();
    }
    
    // função que verifica o campo digitado e faz o Ajax
    function checaEmail(email){
    
       if(checkMail(email)){
          url_="verifica.php?email="+email;
          http.open("GET",url_,true);
          http.onreadystatechange=function(){
             if(http.readyState==4){
                if(http.responseText == "ok"){
                   alert("email existe!");
                }else{
                   alert("email não existe!");
                }
             }
          }
          http.send(null);
       }
    
    }
    
    // função para verificar validade do e-mail
    function checkMail(email) {
    
        invalidChars = " ~\'^\'\"*+=\|][(){}$&!%/:,;ç";
    
        if (email == "") {
            return false;
        }
    
        for (i=0; i<invalidChars.length; i++) {
            badChar = invalidChars.charAt(i);
            if (email.indexOf(badChar,0) > -1) {
                return false;
            }
        }
    
        lengthOfEmail = email.length;
        if ((email.charAt(lengthOfEmail - 1) == ".") || (email.charAt(lengthOfEmail - 2) == ".")) {
            return false;
        }
    
        Pos = email.indexOf("@",1);
        if (email.charAt(Pos + 1) == ".") {
            return false;
        }
    
        while ((Pos < lengthOfEmail) && ( Pos != -1)) {
            Pos = email.indexOf(".",Pos);
            if (email.charAt(Pos + 1) == ".") {
                return false;
            }
            if (Pos != -1) {
                Pos++;
            }
        }
    
        atPos = email.indexOf("@",1);
        if (atPos == -1) {
            return false;
        }
    
        if (email.indexOf("@",atPos+1) != -1) {
            return false;
        }
    
        periodPos = email.indexOf(".",atPos);
        if (periodPos == -1) {
            return false;
        }
    
        if (periodPos+3 > email.length) {
            return false;
        }
        return true;
    }
    

    PHP File:

    In the PHP file you should check the database if the email exists and return the string "ok" by issuing a alert in the above JavaScript (this you can change to do as you wish):

    <?php
       $email = $_GET['email'];
    
       if(isset($email)){
    
          $conexao = mysqli_connect('host do BD', 'usuário', 'senha', 'nome do BD');
          $buscar = "select email from tabela where email='$email'";
          $query = $conexao->query($buscar);
          $numrow = mysqli_num_rows($query);
          if($numrow > 0){
             echo 'ok';
          }
       }
    ?>
    
        
    16.11.2017 / 23:04
    -6

    You need to make a select in your bank that takes all the emails, send to the page that makes the registration and with a for, check if the email you typed already exists, something like

    No HTML:

    <html>
        <script>
            var emails = <?=$emails?>;
            for(i = 0; i < emails.length; i++) { 
                if(emails[i] == email) {
                    //Se tiver um email igual...
                } else {
                   //Senão...
                }
            }
        </script>
        //Código...
    

    $emails is the result of select

    email is the email entered by the user

    There are other ways ...

        
    16.11.2017 / 22:40