How can a PHP function be triggered when a user clicks on a button?
To trigger a PHP function when a user clicks on a button, you can use AJAX to send a request to a PHP script that contains the function you want to execute. This way, the function will be triggered without the need to reload the entire page.
// HTML button that triggers the PHP function
<button id="triggerFunction">Click me</button>
// JavaScript code to send AJAX request when the button is clicked
<script>
document.getElementById('triggerFunction').addEventListener('click', function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'function.php', true);
xhr.send();
});
</script>
// PHP script (function.php) that contains the function to be triggered
<?php
function myFunction() {
// Your PHP function code here
}
myFunction();
?>