Post variable with onclick?

Post variable with onclick?

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

Stefan Bogdanescu

Founder & Senior Architect

The Reality of POSTing via Clickable Links

It is a common misconception in web development that you can seamlessly send $_POST data from one page to another simply by clicking a standard hyperlink. The request you described—triggering a submission without a form or a submit button—is technically impossible using native HTML link behavior. There is no onclick attribute on an <a> tag that allows you to execute a script and magically transform the subsequent navigation into a POST request while keeping the URL clean.

When you click an anchor tag, the browser issues a GET request by default. If you attempt to attach custom logic via JavaScript inside an onclick handler, you are essentially hijacking the navigation event. To achieve your goal of sending data without a visible form, you must use AJAX (Asynchronous JavaScript and XML) or the Fetch API to intercept the click, send the data as POST, and then redirect the browser only after the server responds.

Here is how you would implement this pattern using vanilla JavaScript and the Fetch API. This approach separates the logic of sending data from the act of navigation.

<!-- On first page -->
<a href="#" id="click-me">Click me!</a>

<script>
document.getElementById('click-me').addEventListener('click', function(e) {
    // Prevent default link behavior immediately
    e.preventDefault();

    const variable = ' pertinent_information'; // Your data source
    
    fetch('./page.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams({
            'var': variable
        })
    })
    .then(response => {
        // Handle server response (e.g., check for success)
        if (response.ok) {
            // Now redirect the browser to the target page
            window.location.href = './page.php';
        } else {
            throw new Error('Server error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Submission failed.');
    });
});
</script>

On the receiving end (page.php), you can now safely access the data using $_POST:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $variable = $_POST['var'];
    // Process data...
} else {
    http_response_code(405);
    die('Method Not Allowed');
}
?>

This method ensures that the HTTP verb is indeed POST, satisfying your requirement to avoid GET requests. However, this comes with a significant trade-off: the user experience is not immediate. The browser will not load the new page until the server confirms receipt of the data. If the server processes the data slowly or encounters an error, the user sees a loading state before being redirected.

The alternative you considered in your source material—appending the variable directly to the URL query string (./page.php?var=<?php echo $variable; ?>)—is fundamentally different. That approach relies on URL parameters, which are processed via $_GET, not $_POST. While this is functionally simpler and happens instantly, it exposes your data in the browser history, server logs, and potentially analytics tools. If $variable contains sensitive information (passwords, tokens, or personal details), sending it as a query parameter is a security violation.

There is also a subtle issue with mixing onclick attributes directly into <a> tags with PHP output. While modern frameworks often handle this safely, raw inline event handlers combined with server-side code injection can lead to XSS vulnerabilities if the $variable contains unsanitized user input. By moving the logic to an external script or using addEventListener, you keep your HTML declarative and your JavaScript secure.

If you are working within the Laravel ecosystem, you might find yourself needing similar functionality for redirects based on form submissions. While this specific "link-to-post" pattern is rare in standard MVC architectures (which usually prefer explicit forms), understanding the underlying HTTP mechanics helps when debugging issues where data appears to be lost between views. For more complex state management or SPA-like behaviors within a Laravel app, consider utilizing Livewire components or Vue/React integration, which handle these POST-and-redirect cycles with less manual boilerplate.

Ultimately, if you require silent navigation without user interaction, the only way to guarantee $_POST data is sent is to explicitly construct the request using JavaScript and intercept the standard browser navigation event.

Our network