Skip to content
PHP Logo

How can PHP functions be triggered by event handlers in HTML?

To trigger PHP functions by event handlers in HTML, you can use AJAX calls to send requests to a PHP file that contains the desired function. This way, when the event is triggered in the HTML, it will make a request to the PHP file, which will execute the function and return the result back to the HTML page.

php
// HTML file with event handler
<button onclick="callPHPFunction()">Click me</button>
<script>
function callPHPFunction() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log(this.responseText);
    }
  };
  xhttp.open("GET", "trigger_function.php", true);
  xhttp.send();
}
</script>

// PHP file (trigger_function.php) with the function to be executed
<?php
function myFunction() {
  // Your PHP function code here
  echo "Function executed successfully!";
}

myFunction();
?>