How can I load data into some html text fields when the first loses focus?

0

I have a small conflict with a project that I am working on.

It turns out that I need to load the code of a material, and when it loses its focus, it is necessary to perform a search in the database, take the data from the Materials table and upload it to the two fields that I show in my form.

I find it difficult, since the consultations I do with php, but I can not call a php function from the OnBlur event, I do not know why it does not work for me.

from now, I appreciate the help.

    
asked by Diego Arce 10.10.2018 в 15:10
source

1 answer

3

with ajax you can easily do what you propose the syntax is cencilla and you do not have to write a lot of code, it would be something like ..

 $(document).on('ready',function(){       
     $('#tu-input').on("blur",function(){
          var url = "traer_datos.php";
          $.ajax({                        
             type: "POST",                 
             url: url,                     
             data: $("#formulario").serialize(),//aqui mandarias el valor que quieras enviar para hacer la consulta 
             dataType: 'application/json;charset=utf-8',//debes indicar al ajax que el callback se tratara de un json 
            success: function(data){

           //si la consulta tiene exito ejecutas el codigo que nececites ejemplo
         //puedes inprimir en los inputs el valor del callback asi mas o menos

             $("input").attr("value",data["clave"])  
                   }
               });
            });
        });

and in your php file you capture the value you send through ajax

  <?php   
      $valor= $_POST['x-valor'];

       /*aqui harias tu en base al valor recivido*/
      $sql="SELECT * FROM tuTabla WHERE tuCampo='$valor'";
     /*ejecutar consulta*/
     $query=mysqli_query($link,$sql);//estoy asumiendo que tu variable de conexion a la base de datos se llama $link
      /*si la consulta es exitosa*/
    if($query){
       /*leemos la consulta para imprimirla*/
         $row=mysqli_fetch_array($query);
         $variable=$row["tu_campo_que_decees"];

      /*envias el valor que quieras en un array clave valor este seria el callback*/
        echo json_encode(array("clave"=>$variable));
     }
        ?>

I hope to clarify some doubts you can continue investigating about ajax and php here 'so you can see more or less how it works, good luck!

    
answered by 10.10.2018 / 15:54
source