Vars from PHP to JS and Back

Passing values between PHP (server) and JavaScript (browser) confuses everyone once, because the two run at completely different times: PHP finishes generating the page before the browser even starts executing its JavaScript. Keeping that order in mind makes both directions simple.

PHP to JavaScript: json_encode

Drop a value into the page as a JavaScript literal with json_encode. It handles quoting, escaping and Unicode correctly, so there is no excuse for string-concatenating values into script tags:

<?php
$state = ['user' => 'nina', 'items' => 42, 'labels' => ["O'Reilly", 'ok']];
?>
<script>
  const state = <?php echo json_encode($state, JSON_THROW_ON_ERROR); ?>;
  console.log(state.items); // 42
</script>

Inside HTML text (not script), the equivalent safety net is htmlspecialchars() — encode data for the context you are emitting into.

JavaScript to PHP: an HTTP request

The browser’s variables cannot be “read” by PHP — the server is not listening after the page ships. The only way back is a new request, and fetch makes it a three-liner:

// in the browser
await fetch('/api/save.php', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ items: 42 })
});
<?php
// /api/save.php
$data = json_decode(file_get_contents('php://input'), true);
echo 'received ' . $data['items'];

For classical multi-page forms, the same round trip happens via a hidden <input> synced by JavaScript plus a normal POST — same principle, no XHR.

What not to do

The old-school trick of having PHP print a document.write(...) call and then str_replace the closing tags to smuggle JavaScript output back into the script never actually returned a value to PHP — PHP had already finished executing. It only re-ordered what got printed to the page. If you find that pattern in legacy code, replace it with json_encode plus fetch; it is simpler and it does what the original author intended.

Leave a Reply

Your email address will not be published. Required fields are marked *