View Single Post
  #35    
Old April 9th, 2013, 03:04 PM
Archenoth's Avatar
Archenoth
The arch foe
 
Join Date: Jan 2012
Gender: Male
Nature: Lonely
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:
Code:
<?php
// 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.

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

Code:
<script type='text/javascript'>
  var somevar = <?php echo $var; ?>;
</script>
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>.

Last edited by Archenoth; April 9th, 2013 at 07:40 PM. Reason: Made about 1000x more clear.