John Davidson

javascript - 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:

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

if(document.getElementById('enviarRecibos').clicked == true){
echo $listaDatos;

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:


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

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

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

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

3 of 5 based on 4266 votes


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