How to generate a code in an HTML form that does not already exist

0

I have an HTML form with a "Reference Code" field in which it gives the user the possibility of inserting a code for a product in question that will later be recorded in the DB. Since this field has to be unique and the user does not have to know (obviously) the codes that already exist, I wanted to include, under this field, a button that would generate a code that does not exist in the DB and put that code in the Code input. Here is the HTML code with the field and button:

<div class="control-group">
    <label class="control-label" for="reference">Código de Referência</label>
    <div class="controls">
        <div class="input-prepend input-append">
            <input id="reference"  type="text" name="reference" value="<?php
            if (isset($data['dados_produto']['reference']))
                echo $data['dados_produto']['reference'];
            ?>">
        </div>
    </div>
</div>

<div class="control-group"> 
<div class="controls">
                <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal" id="btn-openform-precos">Gerar Código de Referência</button>
            </div>
        </div>

Generating a code in javascript should not be difficult but the problem will be to access the DB to verify that it no longer exists.

    
asked by anonymous 19.04.2017 / 14:07

1 answer

0

You can use the autocomplete of jquery ui and AJAX how I used #

You make a query in the bank bringing the return in a json, with this you could bring the very code you want.

Here's an example of what it could be:

<?php
//CHAMA A CONEXÃO COM O BANCO DE DADOS
require('../db/conexao.php');

?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title><?php echo $VarEmp ;?></title>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script><scriptsrc="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script><scripttype="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script><scripttype="text/javascript">
  $(document).ready(function(){
    $("input[name='cod']").blur(function(){
      var $cod= $("input[name='cod']");

      $cod.val('Carregando...');


        $.getJSON(
          '../functions/functionCOD.php',
          { cod: $( this ).val() },
          function( json )
          {

            $cod.val( json.Jcod );
          }
        );
    });
  });
  </script>
  </head>
  <body>
      <!--INICIO FORMULARIO DE CADASTRO-->
      <form class="form-horizontal">
        <fieldset>
          <legend>DADOS CADASTRAIS</legend>

            <div class="row">
              <div class="col-md-12">
              <label for="cod">CÓDIGO</label>
                <input type="text" class="form-control" id="cod" name="cod" placeholder="CODIGO DO CLIENTE">
              </div>
            </div>
            <div class="row">
              <div class="col-md-12">
                 <br>
                 <button type="submit" class="btn btn-primary">CADASTRAR</button>
               </div>
              </div>
        </fieldset>
        <!--FINAL FORMULARIO DE CADASTRO-->
      </form>
  </body>
</html>

Your functionCOD.php might look something like this:

<?php
  /**
   * função que devolve em formato JSON os dados do cliente
   */
  function retorna( $cod, $db ){


    $VarStatus =  $cod[0];


    $sql = "SELEC CODIGO+1 FROM CLIENTES WHERE STATUS ='{$VarStatus}'";

    $query = $db->query( $sql );

    $arr = Array();
    if( $query->num_rows )
    {
      while( $dados = $query->fetch_object() )
      {
        $arr['dados']['Jcod'] = $dados-CODIGO



      }
    }
    else
      $arr['dados']['Jcod'] = 'não encontrado';


    return json_encode( $arr );
  }

  if( isset($_GET['cod']) )
  {
    $db = new mysqli('127.0.0.1', 'root', '', 'SISTEMA');

    echo retorna( filter ( $_GET['cod'] ), $db );
  }

  function filter( $var ){
    return $var;
  }
?>

Remembering that it is just an example, I think it would work better

    
19.04.2017 / 15:14