how can I validate input text without using button with PHP, MySQL

0

Good morning I hope you can help me with the problem I have about the validation of this input text ... I have 2 database tables and I need to validate two fields in one table and one field in another table. The detail is that I scan a barcode and that I already have registered in my bd and at the same time another field of status where 2 does not pass or 3 if it happens, so I need that when scanning any code I verify that it has status 3 and at the same time that that code that scan this in the other table that is what is processed in the day then in a few words ....

 **busqueda.php**

    <?php
    $servidor = 'localhost';
    $base_datos = 'net';
    $usuario = 'root';
    $clave = '';
    /* Dos métodos de poner el juego de caracteres en utf-8 */
    $conexion = new PDO(
      "mysql:host=${servidor};dbname=${base_datos};charset=utf8",
      $usuario,
      $clave,
      [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"]
    );

    /* Preparamos la consulta SQL */
    $res = $conexion->prepare('SELECT id, dn, if(pallet_status>=3, "3","2") FROM caratulasalida WHERE dn = :codigo ');
    /* Asignamos el parámetro al valor enviado por POST */
    $res->bindValue(':codigo', $_POST['codigo'], PDO::PARAM_STR);
    /* Ejecutamos la consulta */
    $res->execute();
    /* Devolvemos el registro obtenido como respuesta en JSON */
    header("Content-type: application/json; charset=utf-8");
    echo json_encode($res->fetch(PDO::FETCH_ASSOC));
    ?>

index.html

                                  
        <!-- Modal -->
        <div class="modal fade" id="mostrarmodal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
           <div class="modal-dialog">
              <div class="modal-content">
                 <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h3>Cabecera de la ventana</h3>
             </div>
                 <div class="modal-body">
                    <p>por fin apareci ahora si ya ponme lo que quieras hacer...</p>
             </div>
                 <div class="modal-footer">
                <a href="#" data-dismiss="modal" class="btn btn-danger">Cerrar</a>
             </div>
              </div>
           </div>
        </div>

    <script type="text/javascript">
        $(document).ready(function(){
            $("#codigo").keypress(function(even) {
                //Si fue enter
                //no se 3 es 13 if(even.which == 3) {
                  if(even.which == 13) {
                   //Como tu input lo tienes en un formulario, cuando oprimes enter sometes el formulario y te recarga la página, con esto puedes evitar eso.
                   $("#codigobarras").submit(function(){
                     return false;
                   });
                    //Tu función se llama compruebaCodigo funcionDeValidar($(this).val());
                      compruebaCodigo($(this).val());
                 }
             });

         });

         //En este caso como la url está como primer elemento, si le masdas el código lo toma como la url no como el código function compruebaCodigo(url, codigo){
           function compruebaCodigo(codigo){
                      $.ajax({
                url:'php/busqueda.php',
                type:'post',
                data:{ codigo: codigo},
                success: function(response){
                    if(response==2){
                        console.log("No tiene status aprobatorio"+response);
                    }
                    else if(response==3){
                    //aquí pondrías tu función o código que levanta la ventana modal
                        modal();//Se manda llamar la función
                    }else{
//Adicional puedes poner como un default, encaso de que no responda algo o se ocaionen errores en tu PHP
console.log("Hubo un error al procesar el código");
}
                }
            });

            return false;
        }
    </script>

    +----------------+------------------------------------------------------------+
    | Table          | Create Table |
    +----------------+------------------------------------------------------------+
    | caratulasalida | CREATE TABLE 'caratulasalida' (
      'net_app_po' varchar(250) COLLATE utf8_bin NOT NULL,
      'costumer_np' varchar(250) COLLATE utf8_bin NOT NULL,
      'qty' int(11) NOT NULL,
      'rev' varchar(250) COLLATE utf8_bin NOT NULL,
      'boxes_by_po' int(11) NOT NULL,
      'pallet_status' int(11) NOT NULL,
      'dn' varchar(250) COLLATE utf8_bin NOT NULL,
      'create_date_asn' varchar(250) COLLATE utf8_bin NOT NULL,
      'shipping_address' varchar(250) COLLATE utf8_bin NOT NULL,
      'description' varchar(250) COLLATE utf8_bin NOT NULL,
      'so_no' int(11) NOT NULL,
      'id' int(11) NOT NULL AUTO_INCREMENT,
      PRIMARY KEY ('id')
    ) ENGINE=InnoDB AUTO_INCREMENT=146 DEFAULT CHARSET=utf8 COLLATE=utf8_bin |
    +----------------+-----------------------------------------------------------+
    
asked by fokus 21.06.2018 в 23:23
source

1 answer

1

maybe your question is not clear, but from what I understand is that you want to validate the barcode entered in the text field without the need to press a button, if so, you can do it with javascript or more easy using jQuery, with the keypress event, I understand that the barcode scanners already include the enter, so when you click on enter you can send call the function that goes and validates in the database: something like this

$(document).ready(function(){
$("#campotexto").keypress(function(even) {
     //Si fue enter	   
    	if(even.which == 13) {
        	funcionDeValidar($(this).val());	    	
      }
     });

});

     
function funcionDeValidar(valor){
  alert("Valor a validar: "+ valor);
}
     
 
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<input id="campotexto" type="text" value="">
</body>
</html>

I do not know how you make the call, but whether you use aJax or another method, that can work for you.

For queries you can try a stored procedure that validates the two tables by passing the code something like that.

    create procedure validaCodigo(in codigo int)
          begin
            if exists(select status from Tabla1 where campoCodigo = codigo and status=3) then 
                if exists(select status from Tabla2 where campoCodigo = codigo) then 
                   select 3 as respuesta;
                else
                   select 2 as respuesta;  
                end if;
            else
                select 2 as respuesta; 
            end if;
          end

You can do something like this:

$(document).ready(function(){
$("#campotexto").keypress(function(even) {
     //Si fue enter    
        if(even.which == 13) {
            compruebaCodigo(valida.php,$(this).val());          
      }
     });

});

function compruebaCodigo(url,codigo){
        $.ajax({
                url:url,
                type:"POST",
                data:{ codigo: codigo},

                success: function(response){

                    if(response==2){

                        alert("No tiene status aprobatorio");
                    }
                    else if(response==3){
                        //aquí pondrías tu función o código que levanta la ventana modal
                    }   
                }
            });

            return false;
    }

so your code could be:

<script type="text/javascript">
    $(document).ready(function(){
        $("#codigo").keypress(function(even) {
            //Si fue enter
            if(even.which == 13) {
                funcionDeValidar($(this).val());
             }
         });

     });

     function compruebaCodigo(url,codigo){
        $.ajax({
            url:php/busqueda.php,
            type:"POST",
            data:{ codigo: codigo},
            success: function(response){
                if(response==2){
                    alert("No tiene status aprobatorio");
                }
                else if(response==3){
                //aquí pondrías tu función o código que levanta la ventana modal
                    modal();//Se manda llamar la función
                }
            }
        });

        return false;
    }

 //Se declara la fucnión
function modal(){
    $('#modalserial').on('shown.bs.modal',function () {
    $('#modalserial').trigger('focus')});
}
</script>

Your corrected code

<form id="codigobarras" class="codigo">
        <input type="text" name="codigo" id="codigo" placeholder="Escanear Codigo de Barras del DN" class="codigo" />
        <!--El onkeypres no lo creo necesario, ya que estarías validando dos veces. -->
</form>


    <!-- Modal -->
        <div class="modal fade" id="mostrarmodal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
           <div class="modal-dialog">
              <div class="modal-content">
                 <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h3>Cabecera de la ventana</h3>
             </div>
                 <div class="modal-body">
                    <p>por fin apareci ahora si ya ponme lo que quieras hacer...</p>
             </div>
                 <div class="modal-footer">
                <a href="#" data-dismiss="modal" class="btn btn-danger">Cerrar</a>
             </div>
              </div>
           </div>
        </div>

    <script type="text/javascript">
        $(document).ready(function(){
            $("#codigo").keypress(function(even) {
                //Si fue enter
                //no se 3 es 13 if(even.which == 3) {
                  if(even.which == 13) {
                   //Como tu input lo tienes en un formulario, cuando oprimes enter sometes el formulario y te recarga la página,
                   //con esto puedes evitar eso.
                   $("#codigobarras").submit(function(){
                     return false;
                   });
                    //Tu función se llama compruebaCodigo funcionDeValidar($(this).val());
                      compruebaCodigo($(this).val());
                 }
             });

         });

         //En este caso como la url está como primer elemento, si le masdas el código lo toma como la url
         //no como el código function compruebaCodigo(url, codigo){
           function compruebaCodigo(codigo){
                      $.ajax({
                url:'php/busqueda.php',
                type:'post',
                data:{ codigo: codigo},
                success: function(response){
                    if(response==2){
                        console.log("No tiene status aprobatorio"+response);
                    }
                    else if(response==3){
                    //aquí pondrías tu función o código que levanta la ventana modal
                        modal();//Se manda llamar la función
                    }else{
                        //Adicional puedes poner como un default, encaso de que no responda algo o se ocaionen errores en tu PHP
                        console.log("Hubo un error al procesar el código");
                    }
                }
            });

            return false;
        }
    </script>

Capture the tests I did

Example of connection to MySQL in PHP

conexion.php

<?php 
    $host="localhost";
    $user="root";
    $bd="BD";
    $pass="******";

    $conexion =@mysqli_connect($host,$user,$pass,$bd);
    // if(!$conexion){
    //  echo "Error al conectar";
    // }
    // else{
    //  echo "Conectado";
    // }

 ?>


registro.php

<?php 
include 'conexion.php';

$error;

insertar_marca($conexion);

function insertar_marca($conexion)
{
    global $error;

    $nombre_marca = strtoupper($_POST["nombre-marca"]);
    $insertar ="call registrar_marca ('$nombre_marca')";

    $query = mysqli_query($conexion, $insertar);
    $resultado=mysqli_fetch_assoc($query);
    if (!$query){
        $error=0;
    }
    else{
        if($resultado['error']==1){
            $error=2;
        }
        else{
            $error=1;
        }
    }
    return $error;
}

echo $error;


 ?>
    
answered by 21.06.2018 в 23:38