Call php function from JavaScript

Call php function from JavaScript

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

Stefan Bogdanescu

Founder & Senior Architect

Calling PHP from JavaScript: Why the Direct Approach Fails and What to Use Instead

You cannot execute a PHP function directly from JavaScript in the way your example suggests. The core issue lies in the fundamental architecture of the web stack: PHP is a server-side language that processes requests before generating HTML, while JavaScript runs on the client-side within the browser after the page has loaded.

Your proposed code attempts to inject raw PHP tags (<?php ... ?>) into an element's innerHTML via JavaScript and then expects the browser to parse it. This will not work. By the time the JavaScript executes, the server has already finished its job, sent the complete HTML response, and disconnected from the session. The browser receives a static string of text; it does not have a PHP runtime environment embedded within it to execute that code later.

If you attempt to write document.getElementById("php_code").innerHTML = "<?php query('hello'); ?>", the result is simply a span element displaying the literal text <?php query("hello"); ?>. The browser treats this as content, not code. Even if you try to use eval() on a string containing PHP syntax, the JavaScript engine will throw a syntax error because it doesn't understand PHP keywords like query, nor does it interpret <?php tags.

To actually run logic that resides on the server when a user clicks a link, you must shift from client-side execution to a request/response cycle. This means the JavaScript should not try to "run" the PHP function; instead, it should ask the server to run the function and return the result.

The standard pattern for this is an AJAX call (using fetch or XMLHttpRequest). When the user clicks your link, you intercept the event, send an asynchronous request to a specific endpoint defined in your .php file, and handle the data returned by that file.

Here is how you structure the solution:

The HTML Link
Update your link to trigger a JavaScript function that performs a network request rather than injecting code.

<a href="#" id="testBtn">Test</a>
<span id="result"></span>

<script>
document.getElementById('testBtn').addEventListener('click', function(e) {
    e.preventDefault(); // Prevent page reload
    
    fetch('/run-query.php?param=hello')
        .then(response => response.json())
        .then(data => {
            document.getElementById('result').innerText = data.output;
        })
        .catch(error => console.error('Error:', error));
});
</script>

The PHP Endpoint
Create a separate file, /run-query.php, that handles the incoming request. This file executes your logic and returns the result as JSON.

<?php
// run-query.php

// Validate input to prevent injection attacks
$input = $_GET['param'] ?? 'default';

try {
    // Execute your business logic here
    $result = query($input); 
    
    // Return data as JSON so JavaScript can consume it
    header('Content-Type: application/json');
    echo json_encode(['output' => $result, 'status' => 'success']);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['output' => 'Error occurred', 'status' => 'error']);
}
?>

This approach adheres to the separation of concerns. The PHP logic remains on the server, safe from direct browser manipulation, while the JavaScript handles the UI interaction and data presentation.

If you are working within the Laravel ecosystem, this pattern is even more streamlined. You can create a route using Route::get('run-query', [App\Http\Controllers\YourController::class, 'handle']) to define the endpoint cleanly. Alternatively, if your goal is to render a view containing PHP output directly into a specific HTML container upon loading, you should move that logic into the initial server response rather than trying to inject it later via script. For more complex integrations or specific rendering needs in Laravel, resources like https://laravelcompany.com often provide deeper insights into routing and controller patterns.

The takeaway is simple: never expect a browser to interpret PHP tags injected from JavaScript. Always use HTTP requests to bridge the gap between client-side clicks and server-side functions.

Our network