Run php function on the onclick of a button

1

I need to run the content of a función of In the event onclick of a button, is there any way to do this?

<?php
function accion()
   {
     echo "accion";
    }
?>


<input type="submit" name="" value="Buscar" id="boton1" onclick = "">
    
asked by jose marquez 17.04.2017 в 02:18
source

2 answers

7

It will depend on what you do in the function within PHP , or the value returned by that function. in this case your example performs a echo and returns a value ("action") but without the respective quotes to take it as a string in JavaScript , so it is necessary to add them before printing the value of the function within Javascript . if a string value is not needed, the quotes would be removed before echo in Javascript .

<?php
  function accion(){
    echo "accion";
  }
  function acciondos(){
    echo 19;
  }
?>

<input type="submit" name="" value="Buscar" id="boton1" onclick = "funcion();">
<script>
  function funcion(){
    alert('<?php echo accion(); ?>');
    alert(<?php echo acciondos(); ?>);
    /* Escribir en el Documento*/
    document.write('<?php echo accion(); ?>');
    document.write(<?php echo acciondos(); ?>);
  }
</script>
    
answered by 17.04.2017 / 02:29
source
3

I think it depends on the action you are going to do, in that case if you do it for the onclick event you can make an ajax call to a php file.

//asi queda el archivo que llama
<input type="submit" name="" value="Buscar" id="boton1" onclick = "accion();">
<script>
    function accion()
    {
        $.ajax({
            type:'POST', //aqui puede ser igual get
            url: 'funciones/mifuncion.php',//aqui va tu direccion donde esta tu funcion php
            data: {id:1,otrovalor:'valor'},//aqui tus datos
            success:function(data){
                //lo que devuelve tu archivo mifuncion.php
           },
           error:function(data){
            //lo que devuelve si falla tu archivo mifuncion.php
           }
         });
    }
</script>

//y el archivo mifuncion.php
<?php
//mi accion
echo "accion";
?>
    
answered by 17.04.2017 в 02:25