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

Asked

Viewed 580 times

0

I have an HTML form with a "Reference Code" field in which gives the user the possibility to enter a code for a product in question that will be later saved in the BD. As this field has to be unique and the user does not have to know (obviously) the codes that already exist, I would like to include, below this field, a button that generates a code that does not exist in the BD and puts that code in the input of the Code. Follow 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 javascript code should not be difficult but the problem will be to access the BD to verify that it no longer exists.

  • If you post the table structure and inform what is the field of said code, it is easier for the crowd to help! To check if the code exists in the bd, you need to make a query!

  • I do not advise doing this as any value on the client side can easily be changed via the browser itself. Generate this code on the server side.

  • It is doubtful how the user can not know the codes that already exist, but should enter a new code, and that should be unique.

  • I didn’t understand how to do it @Marco

  • @Vítorsá, forget my second comment, I understood what you meant by the button that generates the code, but still, as I said in the first comment, this is not something so viable since it can be easily changed by the user.

  • You want this code to be displayed to the user for some reason?

Show 1 more comment

1 answer

0


You can use the autocomplete of jquery ui and AJAX how I used here in my case

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

Follows an example basically of how 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>
      <script src="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>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
  <script type="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 could be 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 only an example, but I believe that it would work

Browser other questions tagged

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