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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With