I currently echo certain variables in hidden input fields and read them out with Javascript whenever I need them.
Me and a colleague are now thinking of generating an extra Javascript file with PHP which only contains all variables for Javascript. This way the variables already exist and there is no extra code in the HTML.
What are good ways to pass variables from PHP to Javascript? And how does our solution sound?
General Data Passing
A commonly used exchange format for JavaScript is JSON, using
json_encode. A PHP file like this:then returns a JavaScript object literal like this:
You can directly echo it into a JavaScript variable on your page, e.g.:
…or request it via Ajax (e.g. using jQuery’s getJSON).
Outputting to attributes on tags
If you just need to output a string to an attribute on a tag, use
htmlspecialchars. Assuming a variable:…you can output it like this:
…or if you use short tags: