Question
I have a value in PHP that is created on the server, and I need to use that value inside JavaScript running on the same page.
For example, my PHP code does some API and database work and produces a value:
<?php
$val = $myService->getValue();
Later on that same page, I want to pass $val into JavaScript as an argument:
<script>
// I tried this, but it did not work
myPlugin.start($val);
// This also did not work
<?php myPlugin.start($val); ?>
// This works sometimes, but sometimes it fails
myPlugin.start(<?=$val?>);
</script>
What is the correct and safe way to pass a PHP variable to JavaScript?
Short Answer
By the end of this page, you will understand why PHP variables are not automatically available in JavaScript, how server-side and client-side code interact, and the safest ways to transfer data from PHP to JavaScript using json_encode(), inline script values, and HTML data-* attributes.
Concept
PHP and JavaScript run in different environments:
- PHP runs on the server before the page is sent to the browser.
- JavaScript runs in the browser after the page has been delivered.
That means JavaScript cannot directly read PHP variables such as $val. The PHP variable must first be rendered into the HTML or JavaScript output that the browser receives.
The safest and most common way to do this is with json_encode().
Why json_encode() matters:
- It converts PHP values into valid JavaScript-compatible literals.
- It safely handles strings, quotes, booleans, numbers, arrays, and objects.
- It reduces syntax errors caused by manually inserting raw values.
For example:
<script>
const val = <?php echo json_encode($val); ?>;
myPlugin.start(val);
</script>
If $val is a string like John, json_encode() outputs:
"John"
Mental Model
Think of PHP as a chef in a kitchen and JavaScript as the customer at the table.
- The chef prepares the meal in the kitchen before it leaves.
- The customer only sees what is served on the plate.
A PHP variable is like an ingredient in the kitchen. JavaScript cannot walk into the kitchen and grab it directly. PHP has to place that value onto the plate by writing it into the page output.
json_encode() is like packaging the ingredient in a way the customer can safely use.
Syntax and Examples
Basic pattern: use json_encode()
<?php
$val = $myService->getValue();
?>
<script>
const val = <?php echo json_encode($val); ?>;
myPlugin.start(val);
</script>
Why this works
echoprints the PHP value into the page.json_encode()makes sure the result is valid JavaScript syntax.- JavaScript receives a real value it can use.
Example with a string
<?php
$val = "Hello world";
?>
<script>
const val = <?php echo json_encode($val); ?>;
console.log(val);
</script>
Output in the browser becomes:
Step by Step Execution
Consider this PHP:
<?php
$val = "Book";
?>
<script>
const val = <?php echo json_encode($val); ?>;
myPlugin.start(val);
</script>
What happens step by step
- PHP runs first on the server.
$valis assigned the string"Book".json_encode($val)converts the PHP string into valid JavaScript text:"Book".- PHP sends this final HTML to the browser:
<script>
const val = "Book";
myPlugin.start(val);
</script>
- The browser reads the
<script>block. - JavaScript creates a variable named
val. myPlugin.start(val)runs using the value .
Real World Use Cases
Common practical uses
Passing the current user to frontend code
<script>
const currentUser = <?php echo json_encode([
'id' => $user->id,
'name' => $user->name
]); ?>;
</script>
Used in dashboards, profile pages, and admin tools.
Sending feature flags or settings
<script>
const settings = <?php echo json_encode([
'darkMode' => true,
'itemsPerPage' => 20
]); ?>;
</script>
Useful for frontend behavior controlled by backend configuration.
Preloading form data
<script>
const formDefaults = <?php echo json_encode($formData); ?>;
</script>
Helpful in edit forms and multi-step forms.
Real Codebase Usage
In real projects, developers usually choose one of these patterns:
1. Bootstrapping page data
A page outputs a single object that JavaScript reads on startup.
<script>
window.pageData = <?php echo json_encode([
'user' => $user,
'csrfToken' => $csrfToken,
'cartCount' => $cartCount
]); ?>;
</script>
This is common in server-rendered apps.
2. Element-specific data via data-*
<div
class="user-card"
data-user-id="<?php echo (int)$user['id']; ?>"
data-user-name="<?php echo htmlspecialchars($user['name'], ENT_QUOTES, 'UTF-8'); ?>"
></div>
Common Mistakes
1. Printing raw strings into JavaScript
Broken example:
<?php
$val = "John's book";
?>
<script>
myPlugin.start('<?php echo $val; ?>');
</script>
This can break because the quote inside the string ends the JavaScript string early.
Better:
<script>
myPlugin.start(<?php echo json_encode($val); ?>);
</script>
2. Forgetting that PHP and JavaScript are different languages
Broken example:
<script>
console.log($val);
</script>
$val means nothing to JavaScript unless PHP prints it into the output.
3. Using short echo tags without understanding output
This can be risky if you print unescaped content blindly:
<script>
myPlugin.start(<?=?>);
</script>
Comparisons
| Approach | Best for | Safe for strings? | Handles arrays/objects? | Notes |
|---|---|---|---|---|
json_encode($value) inside <script> | General PHP-to-JS transfer | Yes | Yes | Best default choice |
Raw echo $value inside JS | Simple numbers only | No | No | Easy to break |
data-* attributes | Element-specific values | Yes, with htmlspecialchars() | Limited | Good for small values |
| AJAX/fetch request | Data loaded after page render |
Cheat Sheet
Quick rules
- PHP runs first on the server.
- JavaScript runs later in the browser.
- JavaScript cannot directly access PHP variables.
- PHP must output the value into the page.
- Use
json_encode()for JavaScript values. - Use
htmlspecialchars()for HTML attributes.
Safe pattern
<script>
const value = <?php echo json_encode($value); ?>;
</script>
Safe string example
<script>
const name = <?php echo json_encode($name); ?>;
</script>
Safe array/object example
<script>
const data = <?php echo json_encode($data); ?>;
</script>
For HTML attributes
FAQ
Why can PHP not be accessed directly from JavaScript?
Because PHP runs on the server before the page is sent, while JavaScript runs in the browser after the page loads.
What is the safest way to pass a PHP variable to JavaScript?
Use json_encode() when printing the value into a <script> block.
Can I use <?=$val?> directly?
Only in limited cases, such as simple numeric output. It is not reliable for strings or complex data.
Should I use htmlspecialchars() or json_encode()?
Use json_encode() for JavaScript values. Use htmlspecialchars() for HTML content and attributes.
Can I pass PHP arrays to JavaScript?
Yes. json_encode() converts PHP arrays into JavaScript arrays or objects.
Is it okay to put data into window variables?
Yes, for page bootstrapping or configuration, but keep the structure organized and do not expose sensitive data.
When should I use data-* attributes instead?
Use them when the data belongs to a specific HTML element and does not need to be global.
Can I pass secret API keys from PHP to JavaScript?
Mini Project
Description
Build a small product page where PHP provides product information and JavaScript uses it to initialize frontend behavior. This demonstrates the most common real-world pattern: generating data on the server and safely bootstrapping it into browser code.
Goal
Create a page that passes PHP product data into JavaScript and displays a message using that data.
Requirements
- Create a PHP array with a product id, name, price, and inStock value.
- Pass the product data safely into JavaScript.
- Show the product name and price in the browser console.
- Display a different message depending on whether the product is in stock.
Keep learning
Related questions
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.
Convert a PHP Object to an Associative Array
Learn how to convert a PHP object to an associative array, including quick methods, recursion, pitfalls, and practical examples.
Convert a Postman Request to cURL and PHP cURL
Learn how to convert a Postman POST request into a cURL command and use the same request in PHP cURL with headers and body.