This is a rather common problem for novice web developers. While it may seem at first glance that it’s easy for PHP and JavaScript to communicate with each other, but they actually cannot interact with each other directly. They are very different technologies built for distinct purposes.
How to transfer or pass variable values from PHP to JavaScript?
To pass variables or values from PHP to JavaScript, just write the PHP code to generate the client side JavaScript code as you would with HTML code:
<script>
var jsVar = "<?php echo $phpVar ?>";
</script>
To embed PHP code in *.js files you have to first make the server to parse JavaScript .js files for any PHP code so that they will be executed. After that, you can create classes or call to functions or do whatever that is allowed in PHP in the .js files just as you can with .php files.
How to transfer or pass variable values from JavaScript to PHP?
Simply put, you have no other way to let some PHP script know any variable value than to send a request to it. So, you will use JavaScript to send a request to the PHP script by a GET or POST request that bears the variable value.
You can trigger a redirection to the PHP script and pass the values via URL:
var age = 24;
document.location = 'http://www.example.com/script.php?age=' + age;
Or you can perform an XMLHttpRequest request by GET or by POST.
You should also read:
- PHP: How to distinguish values in $_POST or $_GET that are sent via HTTP requests and those that are set / assigned in the code
- How to execute / run PHP code inside JavaScript files?
- How to pass variable values in URL from page to page with PHP?
- How to include a JavaScript file inside a JavaScript file?
- PHP: Run .CSS files as PHP


Facebook
Twitter
Google Plus
{ 1 trackback }