Call a PHP function after onClick HTML event

Call a PHP function after onClick HTML event

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

Stefan Bogdanescu

Founder & Senior Architect

Why onClick Cannot Call PHP Functions and How to Handle It Correctly

You cannot trigger a PHP function directly from an HTML onClick event on a button. This isn't a limitation of your browser or a missing library; it is a fundamental constraint of how web browsers and servers communicate. When a user clicks a button with the onclick attribute, the event happens entirely within the client-side JavaScript environment running in the browser. PHP code, however, executes on the server before the HTML page is even sent to the user's device.

The architecture creates a one-way street: the server sends data to the client, but the client cannot simply shout back "run this PHP function" and expect the server to execute it immediately without sending new instructions. In your specific scenario, where Admin.php contains both the form and the logic to save contacts to a JSON file, relying on an onClick handler that attempts to bypass the HTTP request lifecycle will fail.

The Architecture of Client-Server Interaction

To understand why your current approach fails, look at the flow of data:

  1. PHP Execution: When a user visits Admin.php, the server executes your PHP code. Variables like $_GET['fullname'] are populated based on query string parameters, not form input, unless the form has been submitted via POST or GET.
  2. HTML Generation: The server generates the HTML response and sends it to the browser. By this point, the PHP script has finished running. The saveContact function exists only in memory on the server during that specific request.
  3. Client-Side Event: When the user clicks the button with onClick="", the browser runs JavaScript. There is no direct pipe from that JavaScript event to the server's PHP execution stack.

If you attempt to call saveContact via client-side code, you are asking the browser to execute server-side logic, which it cannot do. Even if you use jQuery or AJAX to send data back to the server, you must trigger a new HTTP request, effectively restarting the PHP execution cycle rather than invoking a function within the previous one.

The Correct Approach: Form Submission

The standard and most robust way to handle this in your current setup is to let the browser's native form submission mechanism handle the transition. Your HTML shows an input type="submit". When clicked, this element submits the form data to the URL of the page itself (assuming no action attribute is set).

You should modify your PHP logic to listen for a successful POST request rather than trying to intercept the click event. Update your Admin.php to check if the form has been submitted:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Ensure you sanitize inputs here before using them
    $fullname = trim($_POST['fullname'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');

    if (!empty($fullname) && !empty($email)) {
        // Construct the JSON object safely
        $newContact = '{' . 
            '"fullname":"' . htmlspecialchars($fullname, ENT_QUOTES, 'UTF-8') . '",';
        $newContact .= '"email":"' . htmlspecialchars($email, ENT_QUOTES, 'UTF-8') . '",';
        $newContact .= '"phone":"' . htmlspecialchars($phone, ENT_QUOTES, 'UTF-8') . '",';
        $newContact .= '"date_created":' . json_encode(date('c')) . 
            '}';

        // Append to your existing logic safely
        // Note: Appending raw JSON strings to a file is risky for large datasets
        // Consider using json_encode(array_merge($contacts, [$newContact]))
        
        $datafile = fopen("data/data.json", "a+");
        if ($datafile) {
            fwrite($datafile, $newContact . "\n");
            fclose($datafile);
            
            // Optional: Redirect to prevent double submission on refresh
            header("Location: Admin.php"); 
            exit;
        } else {
            echo "<script>alert('Data file not accessible!');</script>";
        }
    }
}

Why Avoid $_GET and Raw String Manipulation?

Your original code attempts to read data using $_GET. This is incorrect because form fields with the name attribute populate $_POST (for submit buttons) or $_GET only if the form method is explicitly set to GET. Using $_GET['fullname'] will likely result in empty strings unless your form tag includes method="get".

Furthermore, building JSON manually by concatenating strings ($new = $new . '"') is prone to errors and security vulnerabilities. You must always sanitize inputs to prevent Cross-Site Scripting (XSS) attacks. The htmlspecialchars function ensures that any special characters in the user's name or email are escaped before being written to the file.

Alternative: AJAX for Page Persistence

If you require the page to remain loaded after adding a contact (avoiding a full reload), you must use JavaScript to send an asynchronous request. You would remove the onClick handler from the button and instead attach a click listener using jQuery:

$('input[type="submit"]').on('click', function(e) {
    e.preventDefault(); // Prevent default form submission
    
    $.post('Admin.php', $(this).closest('form').serialize(), function(response) {
        if (response === 'success') {
            alert('Contact added successfully');
            location.reload(); // Reload to show new data
        }
    });
});

In this version, Admin.php must contain the same POST logic shown above. The PHP file is not modified to have a special endpoint; it simply handles the request if the form data arrives via POST. This preserves the separation of concerns where PHP remains responsible for server-side logic and HTML/JS handle the user interface.

Our network