Efficient way to Pass variables from PHP to JavaScript [duplicate] Efficient way to Pass variables from PHP to JavaScript [duplicate] php php

Efficient way to Pass variables from PHP to JavaScript [duplicate]


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>


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.


<?php// filename: output-json.phpheader('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>