PHP and JavaScript Variable / Value Transfer / Exchange: How to pass variable values from PHP to JavaScript or JavaScript to PHP?

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.

2 thoughts on “PHP and JavaScript Variable / Value Transfer / Exchange: How to pass variable values from PHP to JavaScript or JavaScript to PHP?”

  1. Pingback: Passing variables from Java Script to PHP - NamePros.com

  2. Thanks for the tutorial, I’m still having difficulties with the XMLHttpRequest implementation that you’ve suggested.

    Could you help me please pass the value of myVar into $what_is_myVar (see below):

    var myVar = 123;

Comments are closed.

Scroll to Top