Trigger PHP function by clicking HTML link

Trigger PHP function by clicking HTML link

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Trigger PHP Function by Clicking HTML Link

The short answer is yes, you can trigger a PHP function via an HTML link, but doing so requires moving away from standard URL navigation and into the realm of AJAX or HTTP POST requests. In your specific example, you want to capture $_SESSION['Username'] and insert it into a database table without navigating the user to a new page.

If you simply set the <a> tag's href attribute to a route that executes your listMe function, the browser will perform a full page reload. This means the server processes the request, outputs HTML (likely containing the updated list), and sends it back to the client. The listMe function runs on the server side regardless of whether the output is displayed, but the user experience changes: the screen flickers, layout shifts occur, and any JavaScript state might be lost if not handled carefully.

To achieve the behavior you described—adding a username silently upon clicking—you have two primary architectural paths: using a hidden form with JavaScript to submit data, or leveraging AJAX to send a POST request from the link itself.

The Hidden Form Approach

The most robust and legacy-compatible method involves wrapping the action in a <form> element that submits via POST, even if you hide the form visually. This aligns with how PHP traditionally handles state changes because it keeps the connection alive without requiring complex JavaScript libraries.

You can style the anchor tag to look like a link while embedding it within a form:

<form method="POST" id="addUserForm">
    <input type="hidden" name="username" value="<?php echo htmlspecialchars($_SESSION['Username']); ?>">
    
    <!-- The visible link -->
    <a href="#" onclick="document.getElementById('addUserForm').submit(); return false;">
        Add my username to the list
    </a>
</form>

In this setup, the href attribute points to #, preventing default navigation. When the user clicks the link, the JavaScript triggers the form submission. On the server side, you must ensure your route or script checks for the presence of specific POST data (like a hidden field named username) rather than relying solely on session variables for the database insertion logic, as this provides an extra layer of verification.

The AJAX Approach

If you prefer to keep the formless structure and handle everything via JavaScript, you would need to intercept the click event and send an asynchronous request. This requires a backend endpoint that accepts POST data but does not return a full HTML page. Instead, it should return JSON or simply exit after execution.

// Example: routes/api/add-user.php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    
    // Validation and sanitization are critical here
    if (empty($username)) {
        http_response_code(400);
        exit('Username is required');
    }

    // Securely handle the insertion
    // Note: The source code uses deprecated mysql_* functions. 
    // Modern applications should use PDO or mysqli with prepared statements.
    $stmt = $pdo->prepare("INSERT INTO List (Usernames) VALUES (?)");
    $stmt->execute([$username]);
    
    exit('Success');
}

exit('Method not allowed');

The frontend would then look like this:

<a href="#" id="addLink">Add my username to the list</a>

<script>
document.getElementById('addLink').addEventListener('click', function(e) {
    e.preventDefault(); // Stop default navigation
    
    fetch('/api/add-user', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({ username: '<?php echo $_SESSION['Username']; ?>' })
    })
    .then(response => response.ok ? console.log('Added') : console.error('Failed'))
    .catch(error => console.error('Error:', error));
});
</script>

Critical Security Considerations

The sample code provided in your source material relies on mysql_real_escape_string and direct concatenation into SQL queries. This approach is deprecated as of PHP 5.5.0 and removed in PHP 7.0.0 due to severe security vulnerabilities known as SQL injection attacks. Even if the input seems safe, relying on $_SESSION['Username'] directly without validation is risky.

Furthermore, inserting data based solely on a session value exposes the application to Cross-Site Request Forgery (CSRF) if there are no CSRF tokens protecting the state-changing request. Since you are using an AJAX POST or a hidden form submission, you must implement CSRF protection. If you are building a Laravel application, consider utilizing its built-in CSRF middleware which automatically handles token generation and validation for all state-changing requests.

Finally, always sanitize output when displaying data back to the user. Using htmlspecialchars() on the username before echoing it into an <li> tag prevents Cross-Site Scripting (XSS) attacks if a malicious user manages to inject script tags into your database.

Our network