Passing javascript variables to php?

后端 未结 5 1686
感情败类
感情败类 2020-12-04 03:31

ok so im trying to get a javascript variable into a php script, this would be an example,



        
相关标签:
5条回答
  • 2020-12-04 04:05

    You could use the following Javascript which will link to somepage.php with the variable in the Url

    <script type="text/javascript">
    x = new Date()
    window.location.href = "somepage.php?w1=" + x;
    </script>
    

    This is the contents of somepage.php which recieves the variable and echoes it

    <?php
       if (isset($_GET["w1"])) {
         $x = $_GET["w1"];
         echo $x;
       }else{
       echo 'no variable received';
       }
        ?>
    
    0 讨论(0)
  • 2020-12-04 04:06

    PHP and javascript don't work like that.

    PHP is a server-side language. While javascript is a clientside language.

    There are still ways of passing data from the client-window to your server, via ajax, query parameters, cookies... But none will work in the same page.

    Give us a clearer image on what you are trying to achieve and we will gladly help.

    UPDATE

    JS

    <script type="text/javascript">  
        document.cookie = 'name=Khez' ;  
    </script>  
    

    PHP

    <?php  
        var_dump($_COOKIE['name']);  
    ?>  
    
    0 讨论(0)
  • 2020-12-04 04:08

    So there are 2 pages page1.php and page2.php

    page2.php needs to pass JS variables to page1.php

    We can do this by passing it as url variables from page2.php and get it in page1.php using $_GET[].

    page2.php (send JS variable)

    <script type=text/javascript>
      var lati = location.lat();
      var longi = location.lng();
      document.location = 'http://www.rajak.me/index.php?addlat='+lati+'&addlong='+longi;   
    });
    </script>
    

    page1.php (receive JS variable)

    <?php    
      $addlat = $_GET['addlat'];
      $addlong = $_GET['addlong'];
    ?>
    
    0 讨论(0)
  • 2020-12-04 04:25

    PHP is "Server Side" code and javascript is client side code. They don't interact...

    0 讨论(0)
  • 2020-12-04 04:25

    PHP is server-side~ all parsing is done on the server. JavaScript is client-side~ everything happens AFTER it get's to the client. If you need date in PHP, I recommend time() and or date()

    0 讨论(0)
提交回复
热议问题