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.

<html>
  <body>
    <script>
       var myjavascriptVar=123;
       <?php $myphpVar = 'myjavascriptVar';?>
     </script>
     <?php echo $myphpVar; ?>
  </body>
</html>

Code:

//USING COOKIE

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

<?php
   $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’].

Code:

<script>
  var a="Hello Learners";
  window.location.href = window.location.href+'?a='+a;
</script>

Now your page will reload

<?php
 $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.