How can I call PHP functions by JavaScript?

How can I call PHP functions by JavaScript?

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

Stefan Bogdanescu

Founder & Senior Architect

You Can't Call PHP Functions Directly from JavaScript, But Here's How to Achieve the Same Result

There is a fundamental architectural constraint in web development that often trips up developers new to server-side languages: you cannot call a PHP function directly from a client-side JavaScript script. The code snippet provided in your question illustrates exactly why this happens and attempts to bypass a boundary that does not exist in the standard HTTP request/response cycle.

In the example you shared, you defined functions like add, mult, and divide within a PHP file and attempted to invoke them as if they were global JavaScript variables inside a <script> tag. This approach fails because of how the browser executes code versus how the server processes it. When your web browser renders a page, it parses the HTML and encounters the <script> tag. At that moment, the PHP engine on the server has already finished executing its script and sent only the resulting HTML text to the client. The function definitions (function add...) are never transmitted to the browser; they exist solely in the memory of your PHP process and die when the request ends. Consequently, when the JavaScript parser tries to find a variable named add or mult, it encounters nothing but an undefined reference.

To get values from external PHP into your JavaScript application, you must treat PHP as a data provider and JavaScript as a consumer. The standard mechanism for this is outputting JSON from PHP and parsing that JSON in JavaScript.

Here is how you restructure the code to achieve your goal. First, modify your PHP file to return a structured response instead of trying to expose functions globally. You should wrap your logic in an API endpoint that accepts parameters and returns a JSON object.

<?php
// api.php - The external PHP file acting as the data source

header('Content-Type: application/json'); // Critical: Tells JS this is JSON

function add($a, $b) {
    return $a + $b;
}

function mult($a, $b) {
    return $a * $b;
}

function divide($a, $b) {
    if ($b === 0) {
        throw new InvalidArgumentException("Division by zero is not allowed");
    }
    return $a / $b;
}

// Capture request parameters from the query string or POST body
$operation = $_GET['op'] ?? '';
$val1 = $_GET['v1'] ?? 0;
$val2 = $_GET['v2'] ?? 0;

$response = ['success' => false, 'result' => null];

if ($operation === 'add') {
    $response = ['success' => true, 'result' => add($val1, $val2)];
} elseif ($operation === 'mult') {
    $response = ['success' => true, 'result' => mult($val1, $val2)];
} elseif ($operation === 'divide') {
    try {
        $response = ['success' => true, 'result' => divide($val1, $val2)];
    } catch (InvalidArgumentException $e) {
        $response = ['success' => false, 'error' => $e->getMessage()];
    }
}

echo json_encode($response);

Next, update your JavaScript code to make an HTTP request to this endpoint. Instead of calling add(1,2) directly on the global scope, you send a fetch request to the PHP URL with the operation type and values included in the query parameters.

// client.js or inside an HTML <script> tag

async function performCalculation(operation, val1, val2) {
    // Construct the API URL
    const url = `api.php?op=${operation}&v1=${val1}&v2=${val2}`;

    try {
        const response = await fetch(url);
        const data = await response.json();

        if (data.success) {
            // Use the result from PHP
            console.log(data.result); 
            return data.result;
        } else {
            console.error('PHP calculation failed:', data.error);
            throw new Error('Calculation error');
        }
    } catch (error) {
        console.error('Network or parsing error:', error);
        throw error;
    }
}

// Usage example: calling the PHP logic dynamically
performCalculation('add', 1, 2).then(result => {
    // 'result' will be 3
});

This pattern decouples the business logic (PHP) from the presentation layer (JavaScript). It is robust, scalable, and adheres to security best practices by isolating server-side code. If your original PHP file contains complex logic that doesn't fit this simple query-string model, you would typically refactor it into a dedicated controller or API route within a framework like Laravel, where you can handle routing, validation, and middleware more elegantly.

There are scenarios where developers attempt to use AJAX to return raw HTML containing <script> blocks with pre-calculated values embedded inside. While technically possible to inject JavaScript text from PHP, this approach is generally discouraged in modern development due to security risks involving Cross-Site Scripting (XSS) and the difficulty of managing state. The JSON response pattern described above remains the industry standard for sharing data between backend services and frontend applications.

Our network