how to assign javascript variable value to php variable

前端 未结 8 1536
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 15:12

I have declared a javascript variable ,

 var myJavascriptVar = 12345;

And unable to assign that value to php variable;

相关标签:
8条回答
  • 2020-11-28 15:47
    $msg = "<script>var n=document.getElementById('fil').val; document.write(n);</script>";
    
    echo $msg;
    
    0 讨论(0)
  • 2020-11-28 15:48

    Using Cookie is the better solution i think -

    <script> document.cookie = "myJavascriptVar = " + myJavascriptVar </script>
    <?php
         $myPhpVar= $_COOKIE['myJavascriptVar'];
    ?>
    
    0 讨论(0)
  • 2020-11-28 15:49

    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 );
      });
    
    0 讨论(0)
  • 2020-11-28 15:52

    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>";
        ?>
    
    0 讨论(0)
  • 2020-11-28 15:54

    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:

    <?php 
       if(isset($_POST['isSubmit']))
       {
          // 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"> 
    </form> 
    
    0 讨论(0)
  • 2020-11-28 15:55

    PHP is server side language and JS is client side.best 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";
    </script>
    
    <?php 
       $phpVar =  $_COOKIE['myJavascriptVar'];
    
       echo $phpVar;
    ?>
    
    0 讨论(0)
提交回复
热议问题