W3docs

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.

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:

Example of creating an HTML button with an onclick attribute that calls a JavaScript function when clicked

<button onclick="myFunction()">Click me</button>

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

  1. In the JavaScript function, use the fetch() method to send a request to the PHP script:

Example of using the fetch() method to send a request to the PHP script in the JavaScript function

function myFunction() {
  fetch('path/to/script.php', {
    method: 'POST',
    body: new URLSearchParams({ data: 'test' })
  })
    .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:

Example of using the $_POST or $_GET superglobal arrays to access the data sent in the request, and return a response in PHP

<?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. If testing locally, ensure your server supports CORS or is served from the same origin to avoid browser security restrictions.