简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM