Home > database >  Check a button has been clicked in JS and then do something in PHP
Check a button has been clicked in JS and then do something in PHP

Time:09-27

I'm working in PHP and I have this button, than when clicked, should print something.

I've (unsuccessfully) tried the following:

<?php
echo '<button type="submit" id="enviarRecibos" class="btn btn-primary float-end">Imprimir Lista</button>'; 

?>
<script>
if(document.getElementById('enviarRecibos').clicked == true){
    <?php
    echo $listaDatos;
    ?>
}​;​
</script>

What am I doing wrong?

Note: $listaDatos is a variable that's already in the page with some content in JSON format.

CodePudding user response:

I'm not sure i've well understand what you exactly want, but anyway your javascript script need improvement :

<?php
echo '<button type="submit" id="enviarRecibos" class="btn btn-primary float-end">Imprimir Lista</button>'; 

?>
<script>
document.getElementById('enviarRecibos').addEventListener('click', function (){
    document.getElementById('enviarRecibos').insertAdjacentHTML('afterend', '<?php echo $listaDatos;?>') ;
}) ;
</script>

First the best way to track click on an element in javascript is with addEventListener. Next, you want load content, ok, but you need to define the position / DOM element where the content need to be loaded. You can use "insertAdjacentHTML", an usefull function putting HTML content next to an existing element (here your button). Take care "<?php echo $listaDatos;?>" doesn't contain a quote ' and return a valid HTML string.

AS @brombeer just told you, PHP is a server side language while Javascript is client side. PHP can only help you prepare the raw file code.

  • Related