+ 1

How to pass PHP variable to Javascript and vice versa?

7th Jul 2020, 6:26 AM
Mel
Mel - avatar
4 Answers
+ 2
Here are some example with Php, Js and Css https://code.sololearn.com/wC00Yikflt68/?ref=app
7th Jul 2020, 10:38 PM
Sasha Djekic
+ 3
-------- Mel For passing PHP variable to JS: ---- The technique is to use PHP to dynamically write the JS values you want initialized within <script> tags. -------- For vice versa: ---- You post the JS values back to the PHP page to be evaluated.
7th Jul 2020, 7:25 AM
David Carroll
David Carroll - avatar
+ 3
In your PHP. <?php echo "<script>window.MY_VAR = ${my_var}; </script>"; To pass a JavaScript variable to PHP. Use ajax. With axios it will be like this await axios.post('script.php', {my_var}); then in script.php, $my_var = filter_input('POST', 'my_var', FILTER_SANITIZE_STRING); EDIT -------- I just noticed that you tagged jquery. In jquery, to send a post request is like this. $.post('script.php', {my_var})
7th Jul 2020, 7:26 AM
Ore
Ore - avatar
0
I have long wondered whether it was possible, but so far I don't see it that way. Maybe through your post I find something new.
7th Jul 2020, 7:01 AM
Ipang