JavaScript is Client-side. PHP is Server-side. They can, somehow, talk, but it ain't always so easy.
To use a PHP variable in Javascript, you have to ways, I'd say. The easy way is:
var phpVar = "<?php echo $myVar; ?>";
Or, by echoing:
echo "var phpVar = '{$myVar}';";
But, you'll soon realize this will be printed a little like a constant. This can only be done on the page's rendering, so it's a little limited. It really is, like, if $myVar
contains 5
, to write this directly:
var phpVar = "5";
The results are the same. Another way to use a PHP var in JavaScript is to AJAX-get it. For example, with jQuery:
$.get("/page_that_sends_my_var.php", { }, function(res) {
var phpVar = res;
});
By having page_that_sends_my_var.php
something like this:
<?php
echo $myVar;
But that will be asynchronous. So, you have two different methods for two different purposes. The first one, synchronously, only works when the page is rendering; the second one works whenever you want through an asynchronous call. I'd probably always use the second method; It's more elegant, and AJAX is something nice to do / have: it makes your application more dynamic.
As for using a Javascript variable in PHP, you can do it in 2 ways too. The first one is to use a Form and include the variable in the form's data during the form's submit; the other one (which I prefer) is to use AJAX calls to a PHP script, and send the variable. Like this:
$.post("page_that_uses_my_var.php", { "myVar" : myVar }, function(res) {
// do something if you like
});
Then, in page_that_uses_my_var.php
:
<?php
$jsVar = $_POST["myVar"];