John Davidson

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

0 comments
Message:


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.



My Answer:
You cannot directly trigger PHP code from a button click event in JavaScript. However, you can use AJAX to send a request to a PHP script when the button is clicked.

Here is an example of how you can achieve this:

1. Create a button in your HTML file:

html



2. Add a click event listener to the button in your JavaScript file:

javascript
document.getElementById("myButton").addEventListener("click", function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "your_php_script.php", true);
xhr.send();
});


3. In your PHP script (your_php_script.php), you can then print something:

php
echo "Button clicked!";
?>


When the button is clicked, the JavaScript code will send a GET request to your PHP script, which will then print "Button clicked!".

Make sure to adjust the file paths and names according to your project structure.

Rate this post

4 of 5 based on 5691 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us