show variable php in txt with onclick in button?

0

How can I put the result in the txt when I click on the button? without submit? thanks in advance for the help

<?php



function generarCodigos($cantidad=3, $longitud=10, $incluyeNum=true){ 
    $caracteres = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
    if($incluyeNum) 
        $caracteres .= "1234567890"; 
     
    $arrPassResult=array(); 
    $index=0; 
    while($index<$cantidad){ 
        $tmp=""; 
        for($i=0;$i<$longitud;$i++){ 
            $tmp.=$caracteres[rand(0,strlen($caracteres)-1)]; 
        } 
        if(!in_array($tmp, $arrPassResult)){ 
            $arrPassResult[]=$tmp; 
            $index++; 
        } 
    } 
    return $tmp; 
}  
$codigos=generarCodigos(1,5); 
 


?>



</script>

<html>
<input type="text" name="verificacion" value="">

<input type="button" value="generar codigo" id="code" name="code">
</html>
    
asked by JEFF meza 13.09.2018 в 17:20
source

2 answers

0

Sure. This javascript code can go in your same html file or in a separate one but you must include it in your script in your html.

Your php code will remove it from the html and send it to another file, to that file we will refer to the request of ajax and from that file we will take what your php code returns to us and we will pass it to the input in your html, our intermediary will be the request of ajax in the javscript, do not forget that you need the jquery library to be able to handle events like click () and be able to send information to your input through the val ().

$("#generarMiCodigo").click(function(){
  //Con este evento detectas el click a tu boton y llamas a la función generarCodigo.
alert("me diste click y llame a la función generarCodigo()");
  generarCodigo();
});

function generarCodigo(){
alert("fui llamada.");
  $.ajax({
    url: 'tuArchivo.php',//este es tu archivo php donde estara tu código para generar balga la redundancia tu código.
    type: 'POST',
    dataType: 'JSON',
    data:{
       longitud: 10 //suponiendo que quisieras por ejemplo poder definir desde tu petición la longitud de tu codigo generado este parametro lo tomarias en tu archivo php a travel del $_POST['longitud'];.
    }
  })
  .done(function(respuesta){
       //Si todo salio bien enviamos lo retornado al input.
       $("#codigoGenerado").val(respuesta);
  })
  .fail(function(){
     alert("Si fallo mi consulta de este modo podre estar enterado");
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<html>
<input type="text" id="codigoGenerado" name="verificacion" value="">

<input type="button" id="generarMiCodigo" value="generar codigo" id="code" name="code">
</html>

Obviously this code if you execute it will mark you an error since there is no PHP file, but this is the general idea of the ajax request.

I hope I left it a little clearer.

    
answered by 15.09.2018 / 00:58
source
1

I agree that you should use Ajax, the possible steps that I would recommend, would be:

  • The first thing that would be to get your php code from the function, if the request will be by ajax, you will not really need it if that is the only action you will take.

Example: Your php code

$respuesta = $resultadoDeTuCodigo;
echo json_encode($respuesta);    
?>
  • To color the text in the input , I would add a id to identify it in a more particular way and to send you the information of the PHP file response, for this I would use jQuery.

Example:

 function generarCodigo(){
  $.ajax({
    url: 'url de tur archivo php en tu proyecto',
    type:'POST', //metodo para envio de información
    dataType: 'JSON',//La petición se hara por ajax del mismo modo se 
                 recibira la respuesta
    data:{Si es que tuviese que enviar algun parametro para la operación}
  }),
  .done(function(respuesta){
    //Si la petición fue exitosa tomaremos lo que nos responda el servicio.
     $("#idDelInputText").val(respuesta);//Con esto envias al input la 
      respuesta del servicio.
  })
  .fail(function(){
    //Si falla tu petición, aqui definiras la acción a tomar en caso de 
     dicho resultado
 });
  }

I hope I help you.

    
answered by 13.09.2018 в 21:02