How to call a php script/function on a html button click?

To call a PHP script or function on a HTML button click, you can use JavaScript to send an HTTP request to the server when the button is clicked. The PHP script or function can then handle the request and return a response.

Here is an example of how you might do this:

  1. Create an HTML button with an onclick attribute that calls a JavaScript function when clicked:
<button onclick="myFunction()">Click me</button>

Watch a course Learn object oriented PHP

  1. In the JavaScript function, use the fetch() method to send a request to the PHP script:
function myFunction() {
  fetch('path/to/script.php')
    .then(response => response.text())
    .then(data => {
      // Handle the response from the PHP script
    });
}
  1. In the PHP script, use the $_POST or $_GET superglobal arrays to access the data sent in the request, and return a response:
<?php

  if (isset($_POST['data'])) {
    // Do something with the data
    echo 'Success';
  } else {
    echo 'Error: No data received';
  }
?>

Note that this is a very basic example, and you may need to adjust it depending on the specific requirements of your project.