+ 2

How to get php variable to JavaScript variable

How to get php variable to JavaScript variable

11th Feb 2018, 7:16 PM
Thamindu Sahan Nadeera
Thamindu Sahan Nadeera - avatar
6 Answers
+ 1
You can do this var js = "<?php echo $var ?>";
11th Feb 2018, 9:45 PM
Toni Isotalo
Toni Isotalo - avatar
+ 12
To pass scalar data held in a PHP variable ( $val ) to a JavaScript variable, place the following in a JavaScript segment: var val = " <?php echo $val ?> "; Notice the quotes around the PHP tags. This will result in a string value in JavaScript which you may need to convert for use in your scripts.
18th Feb 2018, 12:53 PM
Abhivarshini Maddala
Abhivarshini Maddala - avatar
+ 8
The two options are presented by @Toni and @WASP. @Toni's approach involves dynamically writing the JavaScript on the PHP page during the initial page request. Your static JS can then run based on the initialized value. @WASP's approach involves loading the PHP generated page on the client, then using AJAX to make a secondary call via Javascript to request the value as JSON or even XML. Which of these options best fit your situation?
12th Feb 2018, 5:19 AM
David Carroll
David Carroll - avatar
+ 5
If you send the variables as query strings you should be able to get them in JS. It's the fastest way I can think of at the moment. https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
11th Feb 2018, 7:43 PM
Mickel
Mickel - avatar
+ 3
ok. thanks all
12th Feb 2018, 1:00 PM
Thamindu Sahan Nadeera
Thamindu Sahan Nadeera - avatar
+ 2
Json?
11th Feb 2018, 7:19 PM
Amir Galanty
Amir Galanty - avatar