如何使用从javascript传递的变量加载PHP页面

I'm new to PHP and am trying to figure something out that I'm sure is very basic. What I am wanting to do is generate variables in javascript and pass these to a PHP page which then loads and displays. The problem is, I seem to be able to both POST variables to the PHP page and load the PHP page but am unable to load the PHP page with the variables that I POSTed.

Here is an example of my code: index.php

...
<script language="javascript">
      function passToPHP(){
          $.ajax({
              type: "POST",
              url: "/TraceExperiment/TraceExperiment.php",
              data: {
                  varToPass: "foo"
              },
              success: function(){
                 window.location.href="/TraceExperiment/TraceExperiment.php";
              }
          })
      }
  </script>
<input type="button", value="displayPHP", onclick="passToPHP()"></input>

TraceExperiment.php

<?php
  $tempVar = $_POST["varToPass"];
  echo("hello" . $tempVar);
  print_r($_POST);
?>

What is happening when I click displayPHP is that the ajax POST succeeds and TraceExperiment.php loads fine (it actually has a whole heap of other html, php etc. code that loads and displays fine but for simplicity I've excluded that) but the $_POST array seems to be empty. i.e. what ends up being displayed when I try to echo and print the POST array and variables is:

Notice: Undefined index: varToPass in C:\xampp\htdocs\TraceExperiment\TraceExperiment.php on line 3 helloArray ( )

Any help resolving this would be much appreciated. Ultimately, I'm simply after a way to display a PHP page that uses variables passed from a javascript file.

You can do a get request like this

 <script language="javascript">
          function passToPHP(){
              var varToPass= "foo"
              window.location = "/TraceExperiment/TraceExperiment.php?varToPass="+varToPass;
      </script>
    <input type="button", value="displayPHP", onclick="passToPHP()"></input>

    <?php
      $tempVar = $_GET["varToPass"];
      echo("hello" . $tempVar);
    ?>

or a post request by creating a simple form

$('#frm').submit(function(e){
  var varToPass= "foo"
   e.preventDefault();
    $(this).find('#varToPass').val(varToPass);
    $(this).submit();
});

<form id ="frm" method="POST" action="/TraceExperiment/TraceExperiment.php">
  <input type="hidden" id="varToPass"/>
  <input type="submit"/>
</form>

dont redirect to the same page on success. you are getting the undefined var on second go to that page

function passToPHP() {
    $.ajax({
        type: "POST",
        url: "/TraceExperiment/TraceExperiment.php",
        dataType:text,
        data: {
            varToPass: "foo"
        },
        success: function(data) {
            console.log(data);
        }
    })
}

try doing like this

if you want to show the message in the html

try

success: function(data) {
    $('body').append(data);
} 

You can dynamically create a form in JavaScript and submit it rather than calling ajax and refreshing the page:

<script language="javascript">
      function passToPHP(){
          $('<form action="/TraceExperiment/TraceExperiment.php" method="POST"><input type="hidden" name="varToPass" value="foo" /></form>').appendTo('body').submit();
      }
  </script>
<input type="button" value="displayPHP" onclick="passToPHP()"></input>

There is 2 solution for This

  • by the different approach

    Generate your variable value by JavaScript and than use

    Write in TraceExperiment.php

        function genratenumber(){
          return "number"
        }
          window.location.href= "/TraceExperiment
        /TraceExperiment.php?yourvar="+genratenumber()
         </script>
       <?php     }else{
         // get the value of $_GET['yourvar']
       } ?>
    

Than get it by using $_GET['yourvar'] on same page

  • By using your approch

    you need to put that variable in session (in ajax file) than only you can get that variable