JavaScript

JavaScript Code in PHP - Embedding & Data Passing

How to use JavaScript inside PHP files - embedding scripts, passing PHP variables to JS, AJAX communication, JSON data exchange, and separation of concerns.

Embedding JavaScript in PHP

PHP runs on the server and generates HTML that the browser receives. JavaScript runs in the browser. When you put JS inside a PHP file, PHP outputs the JS code as part of the HTML, and the browser executes it.

<?php
$pageTitle = 'Dashboard';
$userName = 'Alice';
?>
<!DOCTYPE html>
<html>
<head><title><?= htmlspecialchars($pageTitle) ?></title></head>
<body>
  <h1>Welcome, <?= htmlspecialchars($userName) ?></h1>

  <script>
    // This JavaScript runs in the browser
    console.log('Page loaded for <?= addslashes($userName) ?>');
  </script>
</body>
</html>

Passing PHP Variables to JavaScript

The safest way to pass PHP data to JavaScript is with json_encode():

<?php
$user = [
    'name' => 'Alice',
    'role' => 'admin',
    'permissions' => ['read', 'write', 'delete'],
];

$products = [
    ['id' => 1, 'name' => 'Widget', 'price' => 9.99],
    ['id' => 2, 'name' => 'Gadget', 'price' => 24.50],
];
?>

<script>
  // json_encode outputs valid JavaScript literals
  const user = <?= json_encode($user) ?>;
  const products = <?= json_encode($products) ?>;

  console.log(user.name);           // "Alice"
  console.log(products[0].price);   // 9.99
</script>

Using data-* Attributes

<!-- Pass data via HTML attributes -->
<div id="app"
  data-user-id="<?= $userId ?>"
  data-config='<?= htmlspecialchars(json_encode($config)) ?>'>
</div>

<script>
  const app = document.getElementById('app');
  const userId = app.dataset.userId;
  const config = JSON.parse(app.dataset.config);
</script>

AJAX - Calling PHP from JavaScript

// Modern fetch() approach
async function loadUsers() {
  const response = await fetch('api/users.php');
  const users = await response.json();
  console.log(users);
}

// POST data to PHP
async function saveForm(data) {
  const response = await fetch('api/save.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });
  return response.json();
}

// The PHP endpoint (api/save.php):
// <?php
// $data = json_decode(file_get_contents('php://input'), true);
// // process $data...
// echo json_encode(['status' => 'ok']);

Security: Escaping PHP Output in JS

<?php
$userInput = '</script><script>alert("XSS")</script>';

// DANGEROUS - raw output can break out of script tag
// <script>var x = "<?= $userInput ?>";</script>

// SAFE - json_encode handles escaping
?>
<script>
  var x = <?= json_encode($userInput) ?>;
  // json_encode escapes <, >, & and quotes
</script>

Best Practice: Separate Files

For maintainable code, keep JavaScript in separate .js files and pass configuration data through the DOM rather than embedding PHP inside JS:

<!-- index.php -->
<script>
  // Minimal inline JS: just the PHP data bridge
  window.APP_CONFIG = <?= json_encode([
    'apiUrl' => '/api',
    'userId' => $userId,
    'csrfToken' => $token,
  ]) ?>;
</script>
<script src="app.js"></script>

// app.js (pure JS, no PHP)
const { apiUrl, userId, csrfToken } = window.APP_CONFIG;
fetch(`${apiUrl}/users/${userId}`, {
  headers: { 'X-CSRF-Token': csrfToken }
});

Last updated: 2026 • Browse all courses