Calling a particular PHP function on form submit

Calling a particular PHP function on form submit

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

Stefan Bogdanescu

Founder & Senior Architect

Why display() Can't Be Called Directly in a Form Action Attribute

The code snippet provided attempts to execute a PHP function named display immediately upon form submission by placing its name inside the action attribute of the <form> tag:

<form method="post" action="display()">
    <input type="text" name="studentname">
    <input type="submit" value="click">
</form>

This approach fails because it fundamentally misunderstands how HTML forms and PHP execution contexts interact. The browser interprets the action attribute as a Uniform Resource Locator (URL) or a relative path to an external file, not as a reference to a local function definition. When the user clicks the submit button, the browser sends a POST request to whatever URL is specified in that attribute. Since display() is not a valid URL, the browser likely returns a 404 error or attempts to load a non-existent resource named display().

Even if you remove the parentheses to make it action="display", the behavior remains incorrect. The server would look for a file named display in the current directory (e.g., display.php). If that file does not exist, the request fails. Furthermore, defining a function inside the PHP block at the bottom of the same page does not register it as an executable endpoint on the server; it is merely a script executed after the HTML is parsed by the browser.

The Nature of Form Submission

To understand why this doesn't work, you must distinguish between client-side rendering and server-side logic execution. An HTML form submission is a network event. When you submit data, the browser pauses its current page load, sends the gathered $_POST data (in your case, the value from studentname) to a specific URL defined in the action, and then waits for the response.

The code provided defines the logic (echo "hello" . $_POST["studentname"];) within the same file as the form. However, PHP on the server processes the entire script sequentially. By the time the browser receives the output from a successful request to a valid URL, the HTML has already been sent. You cannot inject a function call directly into the HTTP request lifecycle just by naming it in the action attribute.

Correct Approaches for Single-Page Logic

If your goal is to display data entered in a form on the same page without navigating away, you need to handle the state change within the PHP script itself. There are two standard patterns to achieve this:

Option 1: Process and Redirect (The Standard)
The most robust method involves checking if the form has been submitted using $_SERVER['REQUEST_METHOD']. If it is a POST request, you process the data and then redirect the browser back to the page. This prevents duplicate submissions (the "submit-refresh-submit" problem) and ensures the function logic runs correctly.

<?php
// Check if the form was submitted via POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Extract and sanitize the input
    $studentname = trim($_POST['studentname'] ?? '');
    
    // Your logic here
    echo "hello " . htmlspecialchars($studentname);
}

// Form is always displayed, regardless of submission state
?>
<form method="post" action="">
    <input type="text" name="studentname">
    <input type="submit" value="click">
</form>

In this example, the action attribute is set to an empty string (""). This tells the browser to submit the data to the current script's URL. The PHP code at the top checks if it received a POST request. If so, it executes the logic. Because the output is echoed before the form tags are sent, the result appears on the same page immediately after submission.

Option 2: AJAX or JavaScript Submission
If you strictly require the page to remain interactive without a full reload, you must intercept the form submission using JavaScript. You can prevent the default behavior of the submit button and use fetch or XMLHttpRequest to send the data asynchronously. This allows your PHP function to run in the background, returning JSON or HTML fragments that you inject into the DOM.

<script>
document.querySelector('form').addEventListener('submit', function(e) {
    e.preventDefault(); // Stop full page reload
    
    const formData = new FormData(this);
    
    fetch(window.location.href, { // Submit to current URL
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(data => {
        document.getElementById('result-area').innerHTML = data;
    });
});
</script>

<div id="result-area"></div>

Conclusion on Architecture

Attempting to call a local PHP function directly via the form action attribute conflates navigation with logic execution. Forms are designed to send requests to URLs, not to trigger local code blocks. By separating the submission check ($_SERVER['REQUEST_METHOD']) from the display logic, or by using asynchronous JavaScript, you align your implementation with how the HTTP protocol and PHP runtime actually function. For complex applications requiring these patterns, modern frameworks like Laravel provide robust helpers to manage form state and redirection securely.

Our network