0

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.

1
  • Check your concepts, varToPass is being passed as POST parameter but when you are redirecting user, How come you are expecting varToPass to be present ? In your success callback, you will find processed html Commented Nov 6, 2015 at 6:24

4 Answers 4

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Ahh, this is interesting. So I can actually create a form in javascript and submit it. I wonder whether I could code up a function that takes the array of variables I want to submit and dynamically creates this form.
Yes, you can create a dynamic form and create inputs using array.
1

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>

Comments

1

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);
} 

2 Comments

if @Cam wants to redirect to same page and use value of varToPass for manipulation (rather that just printing), $_SESSION can also be used on TraceExperiment.php page... just a thought
Thanks Pekka. Yeah, as Suyog suggested, I'm more interested in redirecting than simply printing out the response from a php file. Thanks for pointing out that I was attempting to go to the page twice, causing the undefined variable. That makes sense.
1

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

1 Comment

Thanks Shailendra. I think I'll go with either your GET approach or the POST form approach but might check out this $_SESSION thing as perhaps that is most appropriate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.