Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pass javascript variable value to PHP variable 1

Status
Not open for further replies.

peterv12

Technical User
Dec 31, 2008
108
US
This is the first time I've ever tried using Javascript, so please bear with me. I searched for an example on the web, and found something that said it should work, but doesn't. I have a PHP web page that I've added a javascript to that displays a prompt box. (I probably should be using something with an "ok" and "cancel" button.) I want to be able to pass the users answer from the javascript to a variable in the PHP. I've posted the code below, so if someone can tell me where I've screwed this up I'd appreciate it. The javascript is hilighted in red.

Code:
<?php
// Updated: Friday July 10, 2009 - 4:31 AM
//create_tables.php
include("../INCLUDES/dbconnect.php");
//
?>
<html>
<head>
  <title>Drop Author Table Confirmation</title>
  <LINK href="/~peterv/css/mybooks_form.css" type="text/css" rel=stylesheet>
[b][COLOR=red]<script type="text/javascript">
function show_prompt()
{
var reply=prompt("Enter Yes to continue, No to exit");
if (reply!=null && reply!="")
  {
   location.href="create_tables.php?reply=" + reply;
  } else {
     document.write("Invalid entry.")
  }
}
</script>[/color][/b]
</head>
<body>
<!--<h3>* denotes required field!</h3>-->
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<div>
<fieldset><legend><b><em>Select Table To Create</em></b></legend>
<div class="required">
   <label for="author"> Author</label><input type="radio" name="process_what" id="author" value="author"/>
</div>
<div class="required">
   <label for="book"> Book</label><input type="radio" name="process_what" id="book" value="book"/>
</div>
</fieldset>
<fieldset><legend><b><em>Confirm Dropping Table</em></b></legend>
<div class="required">
  <center><h4> You have to DROP the table before creating it.</h4></center>
  <center><h4> Are you 100% SURE????</h4></center><br />
  <!--<label for="name">Drop(Y/N):</label>-->
  <!--<input id="drop" type="text" name="drop" maxlength="21" /><br />-->
  <!--<label for="submit"></label>-->
  <!--<input id="submit" type="submit" value="Drop Table" /><br />-->
  <center><input id="submit" type="button" onclick="show_prompt()" value="Click to confirm" /></center>
</div>
</fieldset>
</div>
<?php
[b][COLOR=blue]$reply = $_POST['reply'];
echo "<br>reply: $reply";[/color][/b] <= returns blank!
  $reply = strtoupper($_POST['drop']);
  $process_what = $_POST['process_what'];
  if ($reply == 'Y') {
     switch ($process_what)  {
     case 'author':
        $query ="DROP TABLE IF EXISTS MYAUTHORS";

        $result = mysql_query($query);
        if (!$result) {
            $message  = 'Invalid query: ' . mysql_error() . "\n";
            $message .= 'Whole query: ' . $query;
            die($message);
        }else{
            echo "Authors table dropped.<br>";
//
            $query ="create table MYAUTHORS
              (authorid INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
               lname VARCHAR(20) NOT NULL,
               mname VARCHAR(20),
               fname VARCHAR(20))";

            $result = mysql_query($query);
            if (!$result) {
                $message  = 'Invalid query: ' . mysql_error() . "\n";
                $message .= 'Whole query: ' . $query;
                die($message);
            }else{
            echo "";
            echo "Authors table created.";
//                $message .= 'Whole query: ' . $query;
//                die($message);
            }
        }
          break;
     case 'book':
          $query ="DROP TABLE IF EXISTS MYBOOKS";
          $result = mysql_query($query);
          if (!$result) {
             $message  = 'Invalid query: ' . mysql_error() . "\n";
             $message .= 'Whole query: ' . $query;
             die($message);
          }
          echo "Books table dropped.<br>";
          $query ="create table MYBOOKS
                  (bookid INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
                   authorid INT NOT NULL,
                   title VARCHAR(60) NOT NULL,
                   isbn VARCHAR(20),
                   type VARCHAR(20) NOT NULL,
                   cover_type  VARCHAR(10) NOT NULL,
                   pages INT,
                   copyright YEAR,
                   date_finished DATE,
                   has_been_read CHAR(01),
                   FOREIGN KEY (authorid) REFERENCES authors (authorid))";

          $result = mysql_query($query);
          if (!$result) {
             $message  = 'Invalid query: ' . mysql_error() . "\n";
             $message .= 'Whole query: ' . $query;
             die($message);
          }
          echo "Books table created.";
          break;
     default:
          $display_block = "Error - no option selected.";
     } // End "switch".
  }elseif (strtoupper($reply) == "N") {
           echo "Books Table NOT dropped.";
  }else{
// no-op.
  }
?>
</form>
</body>
</html>
<?php
 
The PHP is long gone by the time the Javascript runs. The PHP runs on the server, produces the HTML output, then the Javascript runs on the client computer. That means that they don't even run on the same computer, and cannot communicate with each other.

If you would call the Javascript function as soon as the page loads, then whatever page is create_tables.php would be able to get the value passed. However, if that page is the one you showed the code for, if you call the function as soon as the page loads it will keep reloading over and over if you respond Yes to the prompt. You'd have to run the Javascript ONLY if there wasn't a reply value sent in the URL to avoid this kind of problem.

Lee

Lee
 
Actually the only problem is the fact you are looking for reply in the POST super global, however you are sending the value through the URL string in your location.href call, which would put it in the GET super global instead.

So just change :

$reply = $_POST['reply'];

to

$reply = $_[red]GET[/red]['reply'];

Other than that, it should work as expected, since you are reloading the page and passing the reply parameter to it.





----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Good catch, Phil. I missed the call to the function with the submit input.

Rather than use location.href in the function, the function should change the form's action instead to make sure both the form values and the reply value are passed.

Code:
document.forms[0].action="create_tables.php?reply=" + reply;

Lee
 
Phil, I took your suggestion and changed the POST to GET, but when I display the value of $reply I get nothing. Any ideas?
 
Phil, I never doubted you! I figured out the problem. The reference to the file in the href location was missing a subdirectory. I added it, and voila, the value was passed! Thanks to you all. I'm going to search the web for documentation on what the difference between GET & POST is.
Peter V.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top