How do I pass the value of a PHP variable to a javascript in separate file
I have a PHP file:
test.php
<?php
$x = 20;
?>
Now I have a separate html file with javascript:
test.html
<html>
<head>
<script>
//Here I want to check if value of $x in PHP is 20 and print accordingly
//How do I pass the value of $x from the php file to this html file?
</script>
</head>
</html>
Just do this (presuming that your file has a .php file extension):
That, after execution, will leave you with
Which is probably what you want. Now you can freely work with your PHP variable in Javascript. Note that, for this to work, the PHP script that generates the HTML must know about the
$xvariable, so you might want to require it:But as you might know, PHP is executed first (on the server) and then the generated JavaScript is executed on the client, so without technologies such as Ajax or Websockets, it is not possible to communicate with PHP using Javascript in the same manner.