Autocomplete failure

0

I am trying to fill some inputs depending on the value of a main input ... I mean, I have a form inside a div with an id so I can call it from a js

<div id="revisarCliente">

    <form role="form" method="POST" class="formularioVenta">

        <div class="box-body">

            <div class="box">

                <!--=====================================
                ENTRADA DEL CLIENTE
                ======================================--> 

                <div class="form-group">

                    <div class="input-group">

                        <span class="input-group-addon"><i class="fa fa-users"></i></span>

                        <input class="form-control" type="text" id="cliente" name="cliente" value="" placeholder="Nombre de cliente" />

                        <input type="hidden" name="clienteNombre" id="clienteNombre">

                        <span class="input-group-addon"><button type="button" class="btn btn-default btn-xs" data-toggle="modal" data-target="#modalAgregarCliente" data-dismiss="modal">Agregar cliente</button></span>

                    </div>

                </div>

                <!--==============================================
                =            Direccion del cliente            =
                ===============================================-->

                <div class="form-group">

                    <div class="input-group">

                        <span class="input-group-addon"><i class="fa fa-home"></i></span> 

                        <input type="text" class="form-control" id="direccion" name="direccion" value="" placeholder="Direccion de cliente">

                    </div>

                </div>

                <!--====  End of Direccion del cliente  ====-->

                <!--==============================================
                =            Telefono del cliente            =
                ===============================================-->

                <div class="form-group">

                    <div class="input-group">

                        <span class="input-group-addon"><i class="fa fa-phone"></i></span> 

                        <input type="text" class="form-control" id="telefono" name="telefono" value="" placeholder="Telefono de cliente">

                    </div>

                </div>
                <br>

            </div>

        </div>

        <div class="box-footer">

            <button type="submit" class="btn btn-primary pull-right">Guardar Orden</button>

        </div>

    </form>

    <div id="estado">Esperando input.</div>

</div>

in my js I have a code to do the search by ajax and the filling of the other inputs

$(function(){
   /* Ponemos evento blur a la escucha sobre id nombre en id cliente. */
   $('#revisarCliente').on('blur','#cliente',function(){
      /* Obtenemos el valor del campo */
      var valor = this.value;
      /* Si la longitud del valor es mayor a 2 caracteres.. */
      if(valor.length>=3){

         /* Cambiamos el estado.. */
         $('#estado').html('Cargando datos de servidor...');

         /* Hacemos la consulta ajax */
         var consulta = $.ajax({
            type:'POST',
            url:'cliente.php',
            data:{cliente:valor},
            dataType:'JSON'
         });

         /* En caso de que se haya retornado bien.. */
         consulta.done(function(data){
          console.log(data);
            if(data.error!==undefined){
               $('#estado').html('Ha ocurrido un error: '+data.error);
               return false;
            } else {
               if(data.telefono!==undefined){$('#revisarCliente #telefono').val(data.telefono);}
               if(data.direccion!==undefined){$('#revisarCliente #direccion').val(data.direccion);}
               $('#estado').html('Datos cargados..');
               return true;
            }
         });

         /* Si la consulta ha fallado.. */
         consulta.fail(function(){
            $('#estado').html('Ha habido un error contactando el servidor.');
            return false;
         });

      } else {
         /* Mostrar error */
         $('#estado').html('El nombre tener una longitud mayor a 2 caracteres...');
         return false;
      }
   });
});

and I have another in php where I make the connection and search

<?php

/* Conectar a una base de datos de MySQL invocando al controlador */
$dsn = 'mysql:host=localhost;dbname=sistemapos';
$usuario = 'root';
$contraseña = '';

try {
    $gbd = new PDO($dsn, $usuario, $contraseña);
} catch (PDOException $e) {
    echo 'Falló la conexión: ' . $e->getMessage();
}

if(!empty($_POST['cliente'])) { 
    $nombre = $_POST['cliente'];
    $sql = "SELECT * FROM clientes WHERE nombre = :nombre";  
    $stmt = $gbd->prepare($sql);
    $stmt->bindValue(":nombre",$nombre);
    $stmt ->execute();
    $arrDatos = $stmt->fetchAll();

    //Verifica si no hay datos en la consulta
    if($arrDatos){
        foreach ($arrDatos as $row) {
          if ($nombre = $row['nombre']) {
            $return = array ('direccion' => $row['direccion'],
                            'telefono' => $row['telefono'],
                            'nombre' => $row['nombre']);
          }      
        }

    } else {
            //Esto ocurre si el nombre está vacío solamente
            $arrDatos = array('error'=>'El nombre está vacío');
    }

//Imprimir los resultados 
echo json_encode($return);
}

It used to work for me, but now it does not and it only enters the error that there was an error contacting the server

  

Edited

In network I found that and in response I got the data that I'm requesting but I do not print it in the inputs

    
asked by cesg.dav 28.02.2018 в 00:47
source

2 answers

1

Look, your code could be left as follows

<?php

/* Conectar a una base de datos de MySQL invocando al controlador */
$dsn = 'mysql:host=localhost;dbname=sistemapos';
$usuario = 'root';
$contraseña = '';

try {
    $gbd = new PDO($dsn, $usuario, $contraseña);
} catch (PDOException $e) {
    echo 'Falló la conexión: ' . $e->getMessage();
}

if(!empty($_POST['cliente'])) { 
    $nombre = $_POST['cliente'];
    $sql = "SELECT * FROM clientes WHERE nombre = :nombre";  
    $stmt = $gbd->prepare($sql);
    $stmt->bindValue(":nombre",$nombre);
    $stmt ->execute();
    $arrDatos = $stmt->fetchAll();

    //Verifica si no hay datos en la consulta
    if($arrDatos){
        foreach ($arrDatos as $row) {
          if ($nombre = $row['nombre']) {
            // aqui asignas los datos que obtienes de la base de datos
            $return = array ('direccion' => $row['direccion'],
                            'telefono' => $row['telefono'],
                            'nombre' => $row['nombre']);
          }      
        }

    } else {
            //Esto ocurre si el nombre está vacío solamente, o no se encuentran datos en tu base de datos
            $return = array('error'=>'El nombre está vacío');
    }

//Imprimir los resultados 
echo json_encode($return);
}

the $return contains the object so that your ajax call, receives data if in the database, it finds or not the name you are looking for, now if you add it die(json_encode($return)); , makes the impression of the text returned by the function and stops the execution of the script, and your logic is wrong, if you find more than once the name Javier, Pedro or any other, in foreach you overwrite the variable with each one of the results, for which only the last name that is in the database will always be returned to you,

    
answered by 28.02.2018 в 03:18
1

For my part, I carry out this type of consultations in the following way:

Ajax

function creo() {

var id= $("#elid").val();
console.log(id);
$.ajax({

    type:'POST',
    dataType:'json',
    url:'inc/consulta.php',
    data:{id},
    success:function (data) {
        console.log(data);
        console.log(data[0].nombre);
        $("#datito").attr("value",data[0].nombre);
    }
   });
  }

PHP

   <?php
   include('../conn/conexion.php');

   $json   =array();
   $id     =isset($_POST['id']) ? $_POST['id'] : '';
   $sql    ="SELECT * FROM PRODUCTOS WHERE ID_PRODUCTO = $id ";
   $result =mysqli_query($con,$sql) or die ( "Algo ha ido mal en la consulta 
   a la base de datos");

  while ($a = mysqli_fetch_assoc($result)) {

  $json[]=$a;
    # code...
   }
   echo json_encode($json);

    // cerrar conexión de base de datos
  mysqli_close( $con );
  ?>

Also, I think you should see the headers section in the network part. The last result should say something like form-data which is where you can see what data you are sending to the query, since you say it is not done and enter the error that is not contacted with the server.

Greetings

    
answered by 28.02.2018 в 04:52