How to store JavaScript variable value in PHP variable

In this tutorial, we will learn how to store a JavaScript variable value in PHP variable value.  Since one runs on the server side and one runs on the client side. Hope this tutorial will be useful for you and  I will try to make this tutorial easy to learn.

JavaScript Variable into PHP variable

Suppose we have JavaScript and PHP live in the same document, then PHP will be executed first and we know it is executed on the server side and the JavaScript will be executed second and we know that it will be executed on the browser side. In this way, both will never interact.

Let’s understand with an example.

Suppose I declare a JavaScript variable and I am unable to assign that value to PHP. This can be directly resolved using Ajax. But the problem is I don’t know Ajax.

       var myjavascriptVar=123;
       <?php $myphpVar = 'myjavascriptVar';?>
     <?php echo $myphpVar; ?>



<script> document.cookie = "myjavascriptVar = " + myjavascriptVar <?script>

   $myphpVar = $_COOKIE['myjavascriptVar'];


Using Ajax:

The most ideal way to pass the JavaScript variable value in the PHP variable is to pass the JS variable to an AJAX call. But to do this we need to reload the page with the variable in a $_GET parameter and access the variable in PHP using $_GET[‘a’].


  var a="Hello Learners";
  window.location.href = window.location.href+'?a='+a;

Now your page will reload

 $var = $_GET['a'];

Also Read: How to remove a specific value from an array in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *