Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the safest way of passing arguments from server-side PHP to client-side JavaScript [duplicate]

In my application I rely heavily on JavaScript to enhance the user interface, but all of the data comes from a database and is processed by PHP. By default I use 'echo' statements to substitute the required values "just in time" like so:

var myVariable = <?php echo $myVariableInPHP ?> 

This, however, does not strike me as very elegant and I am concerned about stability and maintainability of such code.

Do I have any alternatives here?

For server-side, I am using the Symfony 1.4 PHP framework.

Thanks,

like image 245
Goro Avatar asked Aug 31 '10 20:08

Goro


2 Answers

My favorite way is :

<?php  $var = array(   'prop1' => 'value1',   'prop2' => 'value2',   // ... );  ?> <script type="text/javascript">    var varNameSpace = <?php echo json_encode($var); ?>;     alert( varNameSpace.prop1 ); // -> 'value1' </script> 

Using json_encode() ensures that the values passed to Javascript are escaped and well formatted. Using a common variable container also prevents from over using the global space (window).

like image 94
Yanick Rochon Avatar answered Oct 13 '22 09:10

Yanick Rochon


You might want to use JSON for this, it's really simple to use in both PHP (check json_encode()) and JavaScript.

It's safe to use within <script>-Tags and browsers which understand JavaScript. Note that the PHP function doesn't encode < and >.

Some example PHP:

$user = (object) array("name"=>"Joseph", "age"=>29, "email"=>"[email protected]"); echo '<script type="text/javascript"> var user = '.json_encode($user).'; </script>'; 
like image 23
svens Avatar answered Oct 13 '22 10:10

svens