Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to pass a PHP variable to Javascript? [duplicate]

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?

like image 843
Gregory Bolkenstijn Avatar asked May 04 '10 14:05

Gregory Bolkenstijn


People also ask

Can you pass PHP variable to JavaScript?

We can pass data from PHP to JavaScript in two ways depending on the situation. First, we can pass the data using the simple assignment operator if we want to perform the operation on the same page. Else we can pass data from PHP to JavaScript using Cookies. Cookie work in client-side.

How use JavaScript variable on same page in PHP?

You can easily get the JavaScript variable value on the same page in PHP. Try the following codeL. <script> var res = "success"; </script> <? php echo "<script>document.

How pass data from PHP to JavaScript using AJAX?

ajax({ type: 'POST', url: 'process. php', data: { text1: val1, text2: val2 }, success: function(response) { $('#result'). html(response); } }); });


1 Answers

<?php
  $my_php_var = array(..... big, complex structure.....);
?>
<script type="text/javascript">
  my_js_var = <?=json_encode ($my_php_var)?>;
</script>
like image 101
Javier Avatar answered Sep 20 '22 18:09

Javier