how to assign javascript variable value to php variable

I have declared a javascript variable ,

 var myJavascriptVar = 12345;

And unable to assign that value to php variable;

 $myPhpVar = 'myJavascriptVar'; 

I know Ajax may be the solution of my problem. But i don't know how to use Ajax and solve the problem.

            var myJavascriptVar = 12345;
            <?php $myPhpVar='myJavascriptVar';?> 
        <?php echo $myPhpVar; ?>



Using Cookie is the better solution i think -

<script> document.cookie = "myJavascriptVar = " + myJavascriptVar </script>
     $myPhpVar= $_COOKIE['myJavascriptVar'];

Try using ajax with if you want a more dynamic assignment of variables.

The reason you can't assign a variable directly is because they are processed in different places.

It's like trying to add eggs to an already baked cake, instead you should send the egg to the bakery to get a new cake with the new eggs. That's what jQuery's post is made for.

Alert the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned).

$.post( "test.php", { name: "John", time: "2pm" })
  .done(function( data ) {
    alert( "Data Loaded: " + data );

PHP is server side language and JS is client way to do this is create a cookie using javascript and then read that cookie in PHP

<script type="text/javascript">
    document.cookie = "myJavascriptVar =12345";

   $phpVar =  $_COOKIE['myJavascriptVar'];

   echo $phpVar;
$msg = "<script>var n=document.getElementById('fil').val; document.write(n);</script>";

echo $msg;

I guess you can use cookies for it.

1) First add a cookie jquery plugin.

2) Then store that window width in a cookie variable.

3) Access your cookie in PHP like $_COOKIE['variable name'].


Javascript will be interpreted in Client's browser and you can not assign it to PHP variable which is interpreted on SERVER .

Feasible Solution : You can submit the Javascript value via ajax or through form submit.


You should see these links:

Assign Javascript value to PHP variable

Passing Javascript vars to PHP

Or you can use AJAX request or POST and GET methods to achieve this.

Snippet below may helpful for you:

      // do something here
      echo $_POST["name"];

<form action="<?php $_SERVER['PHP_SELF'];?>" method="POST"> 
Your name: <input type="text" name="name" /> 
<input type="Submit" value="Submit" name="isSubmit"> 


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.