How can I store JavaScript variable output into a PHP variable?

前端 未结 8 1116
时光取名叫无心
时光取名叫无心 2020-11-30 04:09

I have the following code in JavaScript:


PHP Code:-



        
相关标签:
8条回答
  • 2020-11-30 04:44

    If this is related to a form submission, use a hidden inputinside the form and change the hidden input value to this variable value. Then you can get that hidden input value in the php page and assign it to your php variable after form submission.

    Update:

    According to your edit, it seems you don't understand how javascript and php works. Javascript is a client side language, and php is a serverside language. Therefore you cannot execute javascript logic and use that variable value to a php variable when you execute relevant page in the server. You can run the relevant javascript logic after client browser process the web page returned from the web server (which has already executed the php code for the relevant page). After the execution of the javascript code and after assigning the relevant value to the relevant javascript variable, you can use form submission or ajax to send that javascript variable value to use by another php page (or a request to process and get the same php page).

    0 讨论(0)
  • 2020-11-30 04:47

    JavaScript variable = PHP variable try follow:-

    <script>
    var a="Hello";
    <?php
    $variable='a';
    ?>
    </script>
    

    Note:-It run only when you do php code under script tag.I have a successfully initialise php variable.

    0 讨论(0)
  • 2020-11-30 04:58
    <html> 
    <head>
        <script>
            var a="Hello";
        </script>
    
    </head> 
    
    <body> 
        <?php 
            echo $variable = "<script>document.write(a)</script>"; //I want above javascript variable 'a' value to be store here
        ?>
    </body> 
    

    0 讨论(0)
  • 2020-11-30 05:00

    in your view:

      <?php $value = '<p id="course_id"></p>';?>
    

    javascript code:

      var course = document.getElementById("courses").value;
      
     document.getElementById("course_id").innerHTML = course;
    
    0 讨论(0)
  • 2020-11-30 05:03

    You really can't. PHP is generated at the server then sent to the browser, where JS starts to do it's stuff. So, whatever happens in JS on a page, PHP doesn't know because it's already done it's stuff. @manjula is correct, that if you want that to happen, you'd have to use a POST, or an ajax.

    0 讨论(0)
  • 2020-11-30 05:05

    The ideal method would be to pass it with an AJAX call, but for a quick and dirty method, all you'd have to do is reload the page with this variable in a $_GET parameter -

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

    Your page will reload and now in your PHP, you'll have access to the $_GET['a'] variable.

    <?php 
      $variable = $_GET['a'];
    ?>
    
    0 讨论(0)
提交回复
热议问题