Skip to content
PHP Logo

How can a PHP class function be executed when a link is clicked?

To execute a PHP class function when a link is clicked, you can use AJAX to send a request to a PHP script that will instantiate the class and call the desired function. This allows for asynchronous communication between the client-side and server-side code.

php
// index.php
<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
  <a href="#" id="executeFunction">Click here to execute function</a>

  <script>
    $(document).ready(function(){
      $('#executeFunction').click(function(){
        $.ajax({
          url: 'execute_function.php',
          method: 'POST',
          success: function(response){
            console.log(response);
          }
        });
      });
    });
  </script>
</body>
</html>
```

```php
// execute_function.php
<?php
require_once 'YourClass.php';

$yourClass = new YourClass();
$response = $yourClass->yourFunction();

echo $response;
?>
```

```php
// YourClass.php
<?php
class YourClass {
  public function yourFunction() {
    // Your function logic here
    return "Function executed successfully";
  }
}
?>