Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 711
user606521 Avatar asked Jun 04 '12 22:06

user606521


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.

What are the preferred methods for passing variables from PHP for use in an external JavaScript file WordPress?

In order to pass PHP values to a JavaScript file in WordPress you have to make use of the wp_localize_script function. Before you can use the wp_localize_script function to access your localized JavaScript variables, you need to first register the script and then enqueue the script in a PHP file.

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.


2 Answers

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> 
like image 63
ilanco Avatar answered Nov 07 '22 07:11

ilanco


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.

like image 31
biplav Avatar answered Nov 07 '22 06:11

biplav