Prohibit the insertion of repeated data

Asked

Viewed 471 times

1

I need that when typing a text in an input form, it validates right there if there is already this record, that shows the result pro user and does not allow to send the form without changing what is repeated.

form and js:

<form role="form" method="POST" action="php/cadastro.php" accept-charset="utf-8">
  <div class="form-group">
    <label for="exampleInputPassword1">Descrição</label>
    <input type="text" class="form-control" name="descricao" id="descricao" required="required">
  </div>
</form>

    <script type="text/javascript">
    $(function(){ 
      $("input[name='descricao']").on('exit', function(){
        var descricao = $(this).val();
        $.get('arquivo.php?descricao=' + descricao, function(data){ 
          $('#resultado').html(data);
        });
      });
    });
    </script>

php file.

<?php
  $conexao   = mysqli_connect('', '', '', ''); 
  $descricao = filter_input(INPUT_GET, 'descricao');
  $sql       = "SELECT * FROM tabela WHERE descricao = '{$descricao}'";
  $query     = $mysqli->query( $sql ); 
  if( $query->num_rows > 0 ) {
    echo 'Já existe!';
  } else {
    echo 'Não existe ainda!';
  }
?> 

I would like it not to be through a file to check, to check with php in the form itself and already show to the user already realize that can not use such description, without having to go to another file to fetch the record and back to the page.

bank sending file:

$conexao          = mysqli_connect('', '', '', '');
$descricao        = $_POST['descricao'];

$sql            = "INSERT INTO tabela(descricao) VALUES ('$descricao')";

If anyone has any suggestions, I’d appreciate it.

  • You will have to check via ajax in the input Blur event, this is the most basic way, which your code?

  • Ok, post the code you already have and what output it generates. If it is an error, post the error message as well.

  • Okay, I’ll post what I have, but earlier I tried using ajax based on some searches, but it didn’t work.

1 answer

0

A very simple way to implement this behavior would be using listeners about the input and executing a query via ajax to the server to validate the existence of the description in the database. You can have a page with the following code:

<html>
    <head>
        <style type="text/css">
            .message {
                display: none;
            }
        </style>
    </head>
    <body>
        <form role="form" method="POST" action="cadastro.php" accept-charset="utf-8">
            <div class="form-group">
                <label for="descricao">Descrição</label>
                <input type="text" class="form-control" name="descricao" id="descricao" required="required">
                <br/>
                <span class="message"></span>
            </div>
        </form>
        <script
            src="https://code.jquery.com/jquery-3.2.1.js"
            integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
        crossorigin="anonymous"></script>
        <script type="text/javascript">
                $('#descricao').on('change paste keyup', function () {
                    var messageSpan = $('.message');
                    $.get({
                        url: '/valida_descricao.php',
                        data: {'descricao': $(this).val()}
                    }).done(function () {
                        messageSpan.text('Descrição aceita!');
                        messageSpan.css('display', 'inline');
                    }).fail(function () {
                        messageSpan.text('Descrição não aceita!');
                        messageSpan.css('display', 'inline');
                    });
                });
        </script>     
    </body>
</html>

... and a php script called valida_descricao.php for the validation:

<?php
// Obtendo o valor da variável
$descricao = filter_input(INPUT_GET, 'descricao');

// Conectando ao banco de dados
$conexao = mysqli_connect('localhost', 'username', 'password', 'test');
$sql = "SELECT * FROM tabela WHERE descricao = '{$descricao}'";
$query = $conexao->query($sql);
if ($query->num_rows > 0 || empty($descricao)) {
        // Define HTTP Status Code para 403 (HTTP/1.1 403 Forbidden)
        http_response_code(403);
} else {
        // Define HTTP Status Code para 200 (HTTP/1.1 200 OK)
        http_response_code(200);
}

The javascript code flow at the bottom of the page will be controlled according to the HTTP Status Code defined in the server response. And that’s it.

Some of the concepts, techniques and tools used in this implementation: Ajax; HTTP Status Code; Eventtarget.

Browser other questions tagged

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