Efficient way to Pass variables from PHP to JavaScript
Solution 1
If you don't want to use PHP to generate your javascript (and don't mind the extra call to your webserver), use AJAX to fetch the data.
If you do want to use PHP, always encode with json_encode before outputting.
<script>
var myvar = <?php echo json_encode($myVarValue); ?>;
</script>
Solution 2
Please use a rest/rpc api and pass json to your js. This can be done in the following way if you are using jquery:
rest.php
<?php echo "{name:biplav}" ?>
Then From your js make a get call like this:
var js_var;
$.get("rest.php", function(data) {
js_var=data;
});
Thats the simplest example I can think of.
Solution 3
<?php
// filename: output-json.php
header('content-type:application/json;charset=utf-8');
printf('var foo = %s;', json_encode($foo, JSON_PRETTY_PRINT));
json_encode
is a robust function that ensures the output is encoded and formatted as valid javascript / json. The content-type header tells the browser how to interpret the response.
If your response is truly JSON, such as:
{"foo": 5}
Then declare it as content-type:application/json;charset=utf-8
. JSON is faster to parse, and has much less chance of being xss exploited when compared to javascript. But, if you need to use real javascript in the response, such as:
var obj = {foo: 5};
Then declare it as content-type:text/javascript;charset=utf-8
You can link to it like a file:
<script src="output-json.php"></script>
Alternatively, it can be convenient to embed the value directly in your html instead of making a separate http request. Do it like so:
<script>
<?php printf('var foo = %s;', json_encode($foo, JSON_HEX_TAG | JSON_PRETTY_PRINT)) ?>
</script>
Make sure to use JSON_HEX_TAG
if embedding into your html via the <script> tag, otherwise you risk xss injection attacks. There's also other flags you may need to make use of for more security depending on the context you use it in: JSON_HEX_AMP, JSON_HEX_QUOT, JSON_HEX_APOS
. Those flags make the response less human readable, but are generally good for security and compatibility, so you should probably just use them.
I really want to emphasize the importance of declaring the content type and possibly using the JSON_HEX_TAG
flag, as they can both help mitigate xss injection.
Do not do this unless you wish to tempt an xss attack:
<script>
var myvar = <?php echo json_encode($myVarValue); ?>;
</script>
Solution 4
In my opinion, if you need to pass a variable directly in your JS, probably your web application is not good designed.
So, I have two tips:
* Use JSON files for general configurations, like /js/conf/userprefs.json
{
"avatar": "/img/users/123/avatar.jpg",
"preferred_color": "blue"
// ...
}
- or (better way) you can retrieve your json confs with an AJAX call.
With PHP frameworks like Symfony2, you can decide a format in your routing configuration leaving the output of a variable to the template engine (like Twig).
I do an example for Symfony2 users but this can be used by any programmer:
routing.yml
userprefs:
pattern: /js/confs/userprefs.{_format}
defaults: { _controller: CoreBundle:JsonPrefs:User, _format: json }
requirements:
_format: json
_method: GET
Inside the controller you can do all the queries that you need to retrieve your variables putting these in the view:
Resources/Views/JsonPrefs/User.json
{
"avatar": "{{ user.avatar }}",
"preferred_color": "{{ user.preferred_color }}"
// ...
}
Inside your JS now you'll be able to retrieve the JSON with a simple AJAX call. For performance purposes you can cache the JSONs (for example) with Varnish. In this way your server doesn't need to do a query every time you read the user preferences.
Solution 5
If you modify your .htaccess file to include
AddType application/x-httpd-php .js
you can use a .js file and it will be handled by PHP, which is half of what you require.
In terms of how ugly that solution is, I would say that this is the least ugly mechanism. You could try to pass your whole JS script through a PHP script as a string and do a search and replace for the variables you need to insert, but I think that you will agree that this is uglier than the solution you are currently using.
Related videos on Youtube
user606521
Updated on August 08, 2020Comments
-
user606521 over 3 years
From time to time I have to pass some variables from PHP to JS script. For now I did it like this:
var js-variable = "<?php echo $php-variable; ?>";
But this is very ugly and I can't hide my JS script in .js file because it has to be parsed by PHP. What is the best solution to handle this?
-
MaxArt almost 12 yearsI hope this is just an example,
var js-variable
would generate a syntax error, as well as$php-variable
...
-
-
Joseph almost 12 years+1 json is the best way to use data from a PHP script, whether it's via ajax or the the same time as the page is compiled.
-
Pang over 10 yearsWARNING: This can kill your website. Example:
<?php $myVarValue = '<!--<script>'; ?>
. See this question for details. Solution: UseJSON_HEX_TAG
to escape<
and>
(requires PHP 5.3.0). -
biplav almost 10 yearsAnother downside of this is that impacts the inital page load time.
-
Yatko almost 10 years@Pang and biplav, could you be more specific please. stackoverflow.com/q/24855186/1951635
-
Yatko almost 10 years@biplav - how does this affect the performance? I what circumstances? Thanks!
-
biplav almost 10 years@Yatko : The out put of this would be calculated before the page is served from apache to your browser. Suppose, if $myVarValue is calculated by executing a query which takes 500ms. This would add a 500ms delay to initial page load. Another disadvantage is that, to test this query would be tougher compared to an api/rest driven approach. From the point of view of testability and UX rest driven approach is better. Once can easily load the entire page and show the loading symbol for the part of page which uses this variable and then make an ajax call to load that part and build the page.