Check if user name is unique in real time

Asked

Viewed 978 times

6

Hey there, you guys! Currently, to check if a username is unique, I do it in the most basic way. Sending the POST to a PHP page that checks in Mysql, only then returns the error. php.:

<form role="form" action="https://<?php print $_SERVER['HTTP_HOST']; ?>/cadastro/" enctype="multipart/form-data" method="post">
  <div class="form-group">
    <label>Usuário</label>
    <input name="usuario" type="text" class="form-control" minlength="4" placeholder="Digite um usuário único..." required>
  </div>
  <button type="submit" class="btn">Criar</button>
</form>

php checks.:

<?php
  $SqlCheck = $ConDB -> prepare("SELECT COUNT(*) AS `ContUser` FROM 
  `usuarios` WHERE `userName`=:USER;");
  $SqlCheck -> bindParam(":USER", $_POST['usuario']);
  $SqlCheck -> execute();
  $RowCheck = $SqlCheck -> fetch(PDO::FETCH_OBJ);
  $ContUser = $RowCheck -> ContUser;

  if ($ContUser == 0) {
    /* Realiza o cadastro */
  } else {
    echo 'Usuário já existe';
  }
?>

Is it possible to do this check while typing in the input, for example, from the 4 character is shown in the bottom row if the user already exists? In real time?

Maybe in jQuery or ajax you can do, but I don’t know any of these languages.

  • The bad news is that after the 4th character you will stress your server with successive requests.

  • I find this interesting, but I’m not really into it because I never needed it or didn’t find it necessary for my projects. But to avoid the many requests to the bank, which would be bad, perhaps an idea would be to create a text file with all the names of users already registered and, instead of consulting the bank, consult this file. And go updating this file from time to time.

  • Have how many names in the table?

  • Today there is only one. The system is not online yet. I want to learn to do the same in Gmail registration. When he takes the input focus, he says if there is already a user, in the div below: https://uploaddeimagens.com.br/imagens/crie_sua_conta_do_google_-_mozilla_firefox_2017-11-01_21-48-14-png

  • From the fourth character then I would not exist hahaha

  • You can do it in a good way (and without stressing the server) if you make a timer. For example, when the field changes, it waits a little while and does the checking, so it doesn’t just trigger requests while typing. That’s how many systems in production do today. Often the answer lies on the very sites you’ve visited with the feature. Or just do it in the same focus loss, there is much less requisition.

Show 1 more comment

2 answers

2


Page senddata.html

<head>

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

<script type="text/javascript">

function checkname()
{
 var name=document.getElementById( "UserName" ).value;

 if(name.length >3)
 {
      $.ajax({
          type: 'post',
          url: 'checkdata.php',
          data: {
           user_name:name,
          },
          success: function (response) {
               $( '#name_status' ).html(response);
               if(response=="OK")   
               {
                return true;    
               }
               else
               {
                return false;   
               }
          }
      });
 }
 else
 {
  $( '#name_status' ).html("");
  return false;
 }

}

function checkall()
{
 var namehtml=document.getElementById("name_status").innerText;
 alert(namehtml);

 if(namehtml=="OK")
 {
  return true;
 }
 else
 {
  return false;
 }
}

</script>
</head>
<body>

<form method="POST" action="insertdata.php" onsubmit="return checkall();">
 <input type="text" name="username" id="UserName" onkeyup="checkname();">
 <span id="name_status"></span>
 <br>
 <input type="submit" name="submit_form" value="Submit">
</form>

</body>

Page checkdata.php

$mysqli = new mysqli("localhost", "USUARIO", "SENHA", "NOME_DB");

if(isset($_POST['user_name']))
{
 $name=$_POST['user_name'];

 $checkdata=$mysqli->query("SELECT COUNT(*) FROM user WHERE name = '$name'");

 $row = $checkdata->fetch_row();

 if ($row[0] > 0)
 {
  echo "Nome já existe";
 }
 else
 {
  echo "OK";
 }
 exit();
}

Page insertdata.php

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

    $name = $_POST['username'];

    $mysqli = new mysqli("localhost", "USUARIO", "SENHA", "NOME_DB");


    $mysqli->query("Insert into user (name) values ('".$name."')");
}
  • Thank you very much, it worked divinely! It was exactly what I was looking for. Note: at "url: 'checkdata.php'" I needed to change to "url: 'https://meusite.com.br/verificausuario/'", because I used a friendly url and I couldn’t find the file.

0

You could involve in a method this check, and make an event in the click of a Comment calling Ajax to check if there is a user and return a result as the result would do something; Let’s assume you have a Bhutan and when you click on Bhutan the event calls Ajax to go in your php file that has the method Realtime(). In the method vc Return to Ajax a json with the value if true Register successfully made, if it does not display there is already the use.

<?php
public function realTime(){
$SqlCheck = $ConDB -> prepare("SELECT COUNT(*) AS `ContUser` FROM 
`usuarios` WHERE `userName`=:USER;");
$SqlCheck -> bindParam(":USER", $_POST['usuario']);
$SqlCheck -> execute();
$RowCheck = $SqlCheck -> fetch(PDO::FETCH_OBJ);
$ContUser = $RowCheck -> ContUser;

  if ($ContUser == 0) {
   return json_encode('Cadastro Realizado com sucesso!');
  } else {
    return json_encode('Usuário já existe');
  }
}
?>




<button id="verificaUser"></button>

$(document).ready(function(){
   $('#verificaUser').click(function(){
      $.ajax({
       url: 'caminho/da/funcaoQueVericaSeTemOUsuarioNoBanco.php',
       type: 'POST',
       dataType: 'JSON',
       success: function(e){
         alert(e);
       }
      });
   });
})

Browser other questions tagged

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