How do I pass variables and data from PHP to JavaScript?

How do I pass variables and data from PHP to JavaScript?

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

Stefan Bogdanescu

Founder & Senior Architect

How do I pass variables and data from PHP to JavaScript?

When you need to transfer data from a server-side language like PHP to client-side JavaScript, the fundamental rule is simple: you must escape the variable into a string. Browsers cannot execute raw PHP code; they only render HTML, CSS, and standard JavaScript. Attempting to run <script> blocks that contain server-side logic will result in syntax errors because the browser expects valid JS syntax immediately upon parsing the tag.

The Problem with Direct Execution

Your initial attempts illustrate common misconceptions about how data flows between these layers. When you write myPlugin.start($val); inside a <script> block, the browser sees $val as a literal string of characters. It tries to find a variable named "$val" in its JavaScript scope, fails, and throws a reference error. Similarly, placing <?php myPlugin.start($val); ?> directly inside the script tag does not work because the PHP output is treated as text content within the HTML stream until the server has finished processing it.

Even the short echo syntax <script>myPlugin.start(<?php $val; ?>);</script> can be unreliable depending on the variable's type. If $val contains quotes, newlines, or special characters like &, <, or >, injecting them directly into a JavaScript string without proper escaping will break your script. This is why you experienced intermittent failures: sometimes the data was "clean," but as soon as it contained a single quote or an ampersand, the resulting JavaScript became invalid syntax.

The Solution: JSON Encoding

The robust standard for passing data from PHP to JavaScript is to serialize your variables into a JSON string and then parse that string in JavaScript. This approach guarantees that special characters are handled correctly and provides a consistent interface regardless of the data type (strings, numbers, arrays, or objects).

Here is how you should structure your code:

PHP Side:
Instead of echoing the raw value, use json_encode(). This function converts your PHP variable into a JSON-formatted string. Crucially, it handles escaping automatically. For example, if $val contains "He said \"Hello\" & more", json_encode() will output "He said \\"Hello\\" & more" (with the necessary backslashes).

<?php
$val = $myService->getValue(); // e.g., "It's a test & <div>"
$data = json_encode($val); 
?>

JavaScript Side:
On the client side, you parse this JSON string back into a native JavaScript object or primitive using JSON.parse(). This ensures that the data is fully typed and safe to use within your plugin logic.

<script>
    // Retrieve the escaped string from PHP
    const jsonString = "<?php echo $data; ?>";
    
    // Parse it back into a usable JavaScript value
    const val = JSON.parse(jsonString);
    
    // Now pass it safely to your plugin
    myPlugin.start(val);
</script>

Handling Complex Data Structures

If $val is not just a scalar string but an array or an object, the same logic applies. You might have a configuration object that needs to initialize your plugin:

<?php
$config = [
    'apiKey' => $myService->getApiKey(),
    'userId' => $myService->getUserId(),
    'settings' => $myService->getSettings()
];
$jsonConfig = json_encode($config);
?>

In the JavaScript block, JSON.parse() reconstructs this into a proper JS object. This method is superior to simple concatenation because it prevents XSS vulnerabilities if $val originates from user input or untrusted sources. By encoding and decoding, you ensure that the browser treats the data strictly as structured data rather than executable code.

When to Use This Pattern

This pattern is essential whenever your JavaScript relies on server-side state that isn't available in the initial HTML document structure. For instance, if you are building a Single Page Application (SPA) where routes and permissions are determined by PHP logic before hydration, passing these variables via JSON ensures consistency between the server's decision-making process and the client's initialization logic.

If you are working within a Laravel ecosystem, this approach aligns perfectly with how Blade templates handle data injection. While you can use json_encode directly in Blade syntax like {{ json_encode($val) }}, doing so inside a <script> block requires careful attention to escaping rules to avoid breaking the surrounding JavaScript context. Always ensure that the output is treated as a string literal within the script tag, which is exactly what json_encode() provides.

For more advanced data loading scenarios or when dealing with large datasets, consider fetching this JSON via an AJAX request instead of embedding it in the initial page load. However, for simple variable passing during initialization, the encode/decode pattern remains the most reliable and performant solution.

Our network