View Single Post
Old April 9th, 2013 (3:04 PM). Edited April 9th, 2013 by Archenoth.
Archenoth's Avatar
Archenoth Archenoth is offline
The arch foe
Join Date: Jan 2012
Gender: Male
Nature: Lonely
Posts: 467
The two most common ways to get PHP data into JavaScript is to either:

a) Use AJAX with a PHP file that spits out JSON with json_encode(). For example:
// Some code that sets $var to the desired value or array.
echo json_encode($var);
Then use JSON.parse to parse your JSON into a usable JavaScript variable.

b) Echo JavaScript-usable data into the page... For example:

<script type='text/javascript'>
  var somevar = <?php echo $var; ?>;
Be very careful with this approach though since it is very vulnerable to XSS. (Imagine if $var is set to "4; alert('Hi!');" for example...)

For JavaScript to PHP, since PHP is server-side, this requires server activity. You'll either need to use AJAX or reload your current page with the GET or POST variables you want. GET variables are easy since you can fire an AJAX request to someurl?var=<someval>&anothervar=<someothervar>.