Check if username is unique in real time

7

Hello, guys! Currently, to check if a user name is unique, I do the most basic. I send the POST to a PHP page that checks in MySQL, only then returns the error. cadastro.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>

verify.php:

<?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, eg from the 4 character shown on the bottom line if the user already exists? In real time?

Maybe in jQuery or ajax give to do, but I do not handle any of these languages.

    
asked by anonymous 01.11.2017 / 21:34

2 answers

2

Page senddata.html

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><scripttype="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>

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."')");
}
    
02.11.2017 / 15:44
0

You could wrap this check in a method, and make an event in the click of a button by calling Ajax to check if the user exists and return a result as the result you would do something; Let's assume you have a Bhutan and when you click Bhutan the event calls Ajax to go in your php file that has the realTime () method. In the Method vc return to Ajax a json with the value if true Successful Registration, if it does not already exist the user exists.

<?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);
       }
      });
   });
})
    
02.11.2017 / 00:45