Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

<html>
    <body>
        <script>
            var myJavascriptVar = 12345;
            <?php $myPhpVar='myJavascriptVar';?> 
        </script>
        <?php echo $myPhpVar; ?>
     </body>
</html>
like image 924
DKBHOI Avatar asked Feb 07 '14 05:02

DKBHOI


3 Answers

Using Cookie is the better solution i think -

<script> document.cookie = "myJavascriptVar = " + myJavascriptVar </script>
<?php
     $myPhpVar= $_COOKIE['myJavascriptVar'];
?>
like image 101
SM Ataul Karim Riad Avatar answered Oct 01 '22 15:10

SM Ataul Karim Riad


Try using ajax with jQuery.post() 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 );
  });
like image 44
alejandroid Avatar answered Oct 01 '22 14:10

alejandroid


I have a better solution: Here, in the .php file, I have a variable called javascriptVar. Now, I want to assign the value of javascriptVar to my php variable called phpVar. I do this by simply call javascript variable by document.writeln in the script tag.

    <?php 
        echo "<script>
                var javascriptVar = 'success';
             </script>";
        
    
        $phpVar = "<script>document.writeln(javascriptVar);</script>";
    ?>
like image 22
Nazmul81 Avatar answered Oct 01 '22 15:10

Nazmul81