Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  46] [ 1]  / answers: 1 / hits: 15088  / 13 Years ago, sun, may 29, 2011, 12:00:00

Possible Duplicate:

Best way to transfer an array between PHP and Javascript






How do I put the value of a PHP variable inside a Javascript variable?
This is what I have now in a js file:



test=<?php echo $country; ?>;

More From » php

 Answers
18

Don't forget to properly escape your variables before passing them to JavaScript. Use json_encode() for this, as it escapes and encodes your values in a way suitable for using with JavaScript:



test=<?php echo json_encode($country) ?>;


Never simply send the variable un-encoded, as it might break things, or, worse, if the value comes from untrusted sources, compromise your security.



Also, rename your file to .php instead of .js if you want to be able to insert dynamic PHP code inside it.


[#91986] Friday, May 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shawn

Total Points: 507
Total Questions: 103
Total Answers: 111

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
;