Get variable from PHP to JavaScript

Get variable from PHP to JavaScript

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

Stefan Bogdanescu

Founder & Senior Architect

Get variable from PHP to JavaScript

You cannot pass a PHP variable directly to JavaScript in the way you might pass an argument between two functions in the same language. PHP executes on the server, while JavaScript runs in the browser. They exist in separate environments separated by a network request. To bridge this gap, you must serialize the data on the server and deserialize it on the client. The mechanism you choose depends entirely on how your application is architected: are you building a traditional multi-page site or a Single Page Application (SPA)?

HTML Output for Multi-Page Sites

In a traditional setup where PHP renders an HTML page, the most straightforward approach is to embed the variable directly into the HTML response. Since JavaScript executes in the browser after the HTML has been received, any data present in the DOM at load time becomes accessible via standard selectors.

Consider a scenario where you need to pass a user ID from a backend route to a script that fetches additional details:

<?php
$user_id = 12345; // This variable exists on the server
?>
<!DOCTYPE html>
<html>
<head>
    <script>
        // Access the PHP variable as a global variable or via data attributes
        const userIdFromPHP = <?php echo $user_id; ?>;
        
        console.log('Fetching user details for:', userIdFromPHP);
        
        fetch(`/api/users/${userIdFromPHP}`)
            .then(response => response.json())
            .then(data => console.log(data));
    </script>
</head>
<body>
    <h1>User Dashboard</h1>
    
    <!-- Alternative: Use data attributes to avoid global scope pollution -->
    <div id="user-container" data-user-id="<?php echo $user_id; ?>">
        Loading...
    </div>

    <script>
        const container = document.getElementById('user-container');
        const userIdFromAttribute = container.getAttribute('data-user-id');
        
        fetch(`/api/users/${userIdFromAttribute}`)
            .then(response => response.json())
            .then(data => {
                console.log(data);
                container.innerHTML = `<h2>Welcome, User ${data.name}</h2>`;
            });
    </script>
</body>
</html>

In this example, the PHP variable $user_id is echoed directly into the script tag. This works because the browser receives the rendered HTML as a text string containing the actual value 12345. The JavaScript parser then treats it as a literal number. Alternatively, using data-* attributes keeps the data associated with specific DOM elements, which is often cleaner for event-driven logic.

Trade-offs: This method exposes server-side data to the client immediately upon page load. If $user_id contains sensitive information that should not be known until a user authenticates, embedding it in the HTML source is a security risk. You must ensure that any variable passed this way is safe for public consumption or protected by subsequent authentication checks on the API endpoints.

AJAX and JSON Responses

If your application relies on asynchronous data loading without page reloads, you cannot rely on the initial HTML document to carry the variable. Instead, you must make a specific request to an API endpoint that returns the variable as JSON.

// JavaScript client-side code
fetch('/api/session-data')
    .then(response => response.json())
    .then(data => {
        const userId = data.user_id;
        console.log(userId);
    });

On the server side, your PHP endpoint would look like this:

<?php
// Ensure headers are set to JSON
header('Content-Type: application/json');

$data = [
    'user_id' => $user_id, // The PHP variable being passed
    'token' => $_SESSION['auth_token'] ?? null
];

echo json_encode($data);
?>

This pattern decouples data from structure. You can send complex objects, arrays, or configuration states dynamically based on server logic without altering the HTML template. However, it introduces a latency cost: the browser must pause execution to wait for the network response before accessing the variable. This is generally acceptable for dynamic apps but adds unnecessary overhead if the data is constant for the entire session and could have been embedded in the initial render.

Security Considerations

Regardless of the method chosen, never pass untrusted user input directly from a PHP variable into JavaScript code without escaping. If $variable comes from $_GET or $_POST, echoing it directly creates an XSS vulnerability. Always use htmlspecialchars() when embedding variables in HTML contexts:

echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');

When dealing with large amounts of data, consider using Laravel's Blade templating engine if you are working within that ecosystem. It provides syntax sugar for escaping and makes it easier to manage view components safely. For more advanced state management in SPAs built on top of PHP backends, frameworks like Livewire often handle these data transfers automatically behind the scenes.

For developers looking to standardize their approach to server-client data exchange or need deeper insights into Laravel-specific implementation patterns, LaravelCompany offers resources that can help streamline backend-to-frontend integrations.

Our network