How to Pass Data from PHP to JavaScript: Frequently Asked Questions and Answers
\n\nHave you ever written a PHP script, generated an array with data from a database, and then realized with horror that the JavaScript code on the same page knows nothing about it? A familiar situation. PHP runs on the server, JavaScript runs in the user's browser. These are two different worlds, separated by time and space. But how do you make them work together? How do you pass variables and data from PHP to JavaScript?
\n\nThis topic is one of the most popular questions on Stack Overflow (tens of thousands of views!). And for good reason: interaction between server-side and client-side code is a fundamental skill for any web developer. In this article, we will break down 5 proven ways to pass data from PHP to JavaScript, from simple to advanced. Let's go!
\n\nWhy Can't PHP and JavaScript Just Talk?
\n\nBefore diving into the code, let's understand the architecture. When a user requests a page, the following happens:
\n\n- \n
- The server executes the PHP script. \n
- PHP generates HTML (and can embed JavaScript into it). \n
- The server sends the finished HTML code to the browser. \n
- The browser renders the page and executes JavaScript. \n
The key point: PHP executes before JavaScript sees the page. Therefore, passing variables from PHP to JavaScript is only possible during the HTML generation stage. JavaScript cannot "request" data from PHP after the page has loaded (AJAX exists for this, but that's a separate story).
\n\nMethod 1: Embedding PHP Directly into JavaScript (Simplest)
\n\nThe most obvious way is to output a PHP variable directly into the JavaScript code generated by the server. Example:
\n\n<?php\n$userName = "Alexey";\n$userAge = 28;\n?>\n\n<script>\n var name = "<?php echo $userName; ?>";\n var age = <?php echo $userAge; ?>;\n console.log("Hello, " + name + "! You are " + age + " years old.");\n</script>\n\n\nDoes it work? Yes. Is it pretty? Not really. The disadvantages are obvious:
\n- \n
- The code becomes messy and hard to read. \n
- If the variable contains quotes or HTML tags, you will get a syntax error in JavaScript. \n
- Security? Forget it: XSS attacks will thank you. \n
This method is only suitable for simple strings without special characters (e.g., a record ID or page number). For everything else, use the following methods.
\n\nMethod 2: JSON — The King of Data Transfer
\n\nJSON (JavaScript Object Notation) is the standard format for exchanging data between a server and a client. PHP can turn any array or object into JSON with a single function json_encode(). JavaScript, in turn, easily parses JSON.
Example: passing an array of users from PHP to JavaScript.
\n\n<?php\n$users = [\n ['name' => 'Ivan', 'age' => 25],\n ['name' => 'Maria', 'age' => 30],\n ['name' => 'Petr', 'age' => 35]\n];\n$jsonUsers = json_encode($users, JSON_UNESCAPED_UNICODE);\n?>\n\n<script>\n var users = <?php echo $jsonUsers; ?>;\n console.log(users[0].name); // "Ivan"\n console.log(users.length); // 3\n</script>\n\n\nWhy is this great?
\n- \n
- Safe:
json_encode()automatically escapes special characters. \n - Universal: pass strings, numbers, arrays, objects, boolean values. \n
- Clean: the code is easy to read and maintain. \n
The only nuance is that the data is embedded directly into the page's HTML code. If there is a lot of data, the page will become heavier. But for most tasks, this is the optimal option.
\n\nMethod 3: HTML data-attributes (for passing via the DOM)
\n\nSometimes you need to pass data associated with a specific element on the page. For example