0

Hi,

It is kind of difficult to explain what I am trying to do here, I will provide the form here to give a better idea.

<ul>
<li>Select the type of your starting point of interest:<br/>
<div id="start_menu"><form action="test_getrss.php" name="form1" method="post">
<span><input type="radio" value="Apartment" name="start"
onclick="check(document.form1.start)"/> Apartment </span>
<span><input type="radio" value="Grocery" name="start"
onclick="check(document.form1.start)"/> Grocery </span>
<span><input type="radio" value="Drugstore" name="start"
onclick="check(document.form1.start)"/> Drug Store </span>
</form></div></li>
<li>Select the type of your ending point of interest:<br/>
<div id="end_menu"><form action="test_getrss2.php" name="form2" method="post">
<span><input type="radio" value="Apartment" name="end"
onclick="check2(document.form2.end)"/> Apartment </span>
<span><input type="radio" value="Grocery" name="end"
onclick="check2(document.form2.end)"/> Grocery </span>
<span><input type="radio" value="Drugstore" name="end"
onclick="check2(document.form2.end)"/> Drug Store </span>
</form></div></li>
<form action="process.php" method="post">
<li>Start Time: <input type="text" size="12" name="start_time"/></li>
<li>Arrive Time: <input type="text" size="12" name="end_time"/></li>
<li>Which Semster is this: <select name="semester">
<option value="Fall">Fall</option>
<option value="Spring">Spring</option>
<option value="Summer">Summer</option>
</select><br/></li>
<input type="hidden" name="form1" value="<?php echo $start?>"/>
<input type="hidden" name="form2" value="<?php echo $end?>"/>
<li style="list-style:none"><input type="submit" value="Submit" name="submit"/>
<input type="reset" value="Reset" name="reset"/></form>

</ul>

For some reason, when I pass in the output with process.php, the hidden input does not get passed in. Here is the process.php:

<?php
//get the q parameter from URL

$start_time = $_POST;
$end_time = $_POST;
$semester = $_POST;
$form1 = $_POST;
$form2 = $_POST;

echo "Start Time " . $start_time . "<br />";
echo "End Time " . $end_time . "<br />";
echo "Semester " . $semester . "<br />";
echo "Start Location " . $form1 . "<br />";
echo "End Location " . $form2 . "<br />";

?>

I get values for start_time, end_time and semester, but not the last two values. What have I done wrong here? BTW, the first two forms, I created them using Ajax, if that helps on solving my issues here.

Thanks for your help.

Alice

4
Contributors
9
Replies
10
Views
7 Years
Discussion Span
Last Post by ajwei810192
0

Hey Alice.

Are you sure PHP is providing them with values in the first place? Check the actual HTML sent to your browser. Make sure the values are there.

Also, one thing that jumped at me when I read that. Your hidden inputs are named "form1" and "form2", but you have already named the first two <form> elements using those same names. You really should avoid that, and keep names unique. (It's not perhaps "needed" as such, but a good practice. Avoids confusions.)

P.S.
Let me just re-post your HTML here, in a more human-readable way, for the benefit of future readers. It's hard to read it like that, especially without the [code] tags. (P.P.S. The [code] tags are your friends!)

<ul>
    <li>Select the type of your starting point of interest:<br/>
        <div id="start_menu">
            <form action="test_getrss.php" name="form1" method="post">
                <span><input type="radio" value="Apartment" name="start"
                         onclick="check(document.form1.start)"/> Apartment </span>
                <span><input type="radio" value="Grocery" name="start" 
                         onclick="check(document.form1.start)"/> Grocery </span>
                <span><input type="radio" value="Drugstore" name="start" 
                         onclick="check(document.form1.start)"/> Drug Store </span>
            </form>
        </div>
    </li>
    <li>Select the type of your ending point of interest:<br/>
        <div id="end_menu">
            <form action="test_getrss2.php" name="form2" method="post">
                <span><input type="radio" value="Apartment" name="end" 
                        onclick="check2(document.form2.end)"/> Apartment </span>
                <span><input type="radio" value="Grocery" name="end" 
                        onclick="check2(document.form2.end)"/> Grocery </span>
                <span><input type="radio" value="Drugstore" name="end" 
                        onclick="check2(document.form2.end)"/> Drug Store </span>
            </form>
        </div>
    </li>
    <form action="?" method="post">
        <li>Start Time: <input type="text" size="12" name="start_time"/></li>
        <li>Arrive Time: <input type="text" size="12" name="end_time"/></li>
        <li>Which Semster is this: 
            <select name="semester">
                <option value="Fall">Fall</option>
                <option value="Spring">Spring</option>
                <option value="Summer">Summer</option>
            </select><br/>
        </li>
        <input type="hidden" name="form1" value="<?php echo "start"; ?>" />
        <input type="hidden" name="form2" value="<?php echo "end"; ?>" />
        <li style="list-style:none">
            <input type="submit" value="Submit" name="submit"/>
            <input type="reset" value="Reset" name="reset"/>
    </form>
</ul>

Also note that the end </li> tag is missing for that last one, and seeing as this appears to be XHTML, it is required.

0

Well, I am not sure. For some reason, when I select and make my options, the code view from the PHP after I pass the requests of the end_menu and start_menu forms, I don't see the "code" with the "select menu" on the output. I still see the radio button even though the output gives me the select drop down. In other words, if PHP is not handling it here, then who/what is? How can I pass the variables on?

0

Ok, I'm not following you 100%.

As I am understanding this, the two first forms, contained in the "start_menu" and "end_menu" divs, are created dynamically with JavaScrip based on values retrieved with AJAX. And you want the choice you make in those forms to be passed to the hidden inputs in the third form, which is submitted the old fashion way.

If so, then why not just move the radio buttons from the first two forms into the third form, so they will be passed along normally? (Meaning; you don't have to copy the values into hidden elements. You can just use the original once.)

Alternatively, if you really need them to be in separate forms, copying the values using JavaScript is fairly simple. Something like this usually does the trick:

/** 
 * Copies the "value" from one element to another 
 */
function copyValue(from, to) {
    if(typeof from != "undefined" && typeof to != "undefined") {
        // If the "to" element is a string, assume it is an element ID.
        if(typeof to == "string") {
            to = document.getElementById(to);
        }
        to.setAttribute("value", from.getAttribute("value"));
    }
}
<body>
    <!-- The non-submitted form, for the radio buttons. -->
    <form id="start_form" name="start_form" action="nowhere.php" method="post">
        <input type="radio" name="start" value="First" onchange="copyValue(this, 'start_hidden');">First<br>
        <input type="radio" name="start" value="Second" onchange="copyValue(this, 'start_hidden');">Second<br>
        <input type="radio" name="start" value="Third" onchange="copyValue(this, 'start_hidden');">Third<br>
    </form>
    
    <!-- The form that gets submitted; the one with the hidden, copied value -->
    <form id="theForm" action="?" method="post">
        <input type="text" name="SomethingVisible">
        <input type="hidden" name="start_value" id="start_hidden" value="none">
        <input type="submit">
    </form>
</body>
0

I think I am missing what you are suggesting here. If it is passed only once here, then where is it doing the searching for tarthe dynamic part of the menu?

The form started out with start_memu and end_menu with radio buttons. The users then picks something from the radio button in the first set, and then the form would generate a new set of dynamic form based on what he/she picks. Then, the user is going to select the second set, and I want to pass in the values of both what what he/she picks from the select menu on to the final output so I could put it in the database.

For some reason, I am having issue passing the information to the output of what the user picks from the dynamic menu and not the "radio" button.

Here is the main file I would like to use for my data entry:

Main:

<?php
// Make a MySQL Connection
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("yyy") or die(mysql_error());

//The variables posted from the PHP form
$start = $_POST["start"];

?>
 <ul>
                <form action="" method="post">
                <li>Select the type of your starting point of interest:<br/>
                                <div id="start_menu"><form action="test_getrss.php" name="form1" method="post">
                                        <span><input type="radio" value="Apartment" name="start"
                                                onclick="check(document.form1.start)"/> Apartment </span>
                                        <span><input type="radio" value="Grocery" name="start"
                                                onclick="check(document.form1.start)"/> Grocery </span>                                               
                                </form></div></li>  </ul>          

  <form action="process.php" method="post">
                     
                        <input type="hidden" name="form1" value="<?php echo $start?>"/>
                       <input type="submit" value="Submit" name="submit"/>
                        <input type="reset" value="Reset" name="reset"/>
                        </form>
        
</body>
</html>

This is the script that I use to construct the drop down menu in test_getrss.php

<?php
//get the q parameter from URL
// Make a MySQL Connection
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxxe") or die(mysql_error());
$q=$_GET["q"];

$query="SELECT name FROM start_from WHERE type='" . $q . "'";
//find out which feed was selected
$result = mysql_query ($query);
echo "<select name='start_location'>";
// printing the list box select command

while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value=$nt[0]>$nt[0]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
?>

See, I am trying to get the users pick something from the <select name="start_location"> and have the info in there to pass on to process.php

<?php
//get the q parameter from URL
// Make a MySQL Connection
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("yyy") or die(mysql_error());
$form1 = $_POST['form1'];

echo "Start Location " . $form1 . "<br />";

?>

Here is what I got in my js file:

function check(field)
{
  var str ="";
  for (i=0;i<field.length;i++)
  if (field[i].checked==true) str = field[i].value + " ";  
  start_menu();
  var url = "getrss.php?q=" + str;
  xmlhttp.open("GET",url,true);
  xmlhttp.send();
  
}

function start_menu() {

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200){
    document.getElementById("start_menu").innerHTML=xmlhttp.responseText
    }  
  if(xmlhttp.responseText == " ") alert("Unable to process request");
  }
}

Am I getting close to pointing out what I am missing here?

Ok, I'm not following you 100%.

As I am understanding this, the two first forms, contained in the "start_menu" and "end_menu" divs, are created dynamically with JavaScrip based on values retrieved with AJAX. And you want the choice you make in those forms to be passed to the hidden inputs in the third form, which is submitted the old fashion way.

If so, then why not just move the radio buttons from the first two forms into the third form, so they will be passed along normally? (Meaning; you don't have to copy the values into hidden elements. You can just use the original once.)

Alternatively, if you really need them to be in separate forms, copying the values using JavaScript is fairly simple. Something like this usually does the trick:

/** 
 * Copies the "value" from one element to another 
 */
function copyValue(from, to) {
    if(typeof from != "undefined" && typeof to != "undefined") {
        // If the "to" element is a string, assume it is an element ID.
        if(typeof to == "string") {
            to = document.getElementById(to);
        }
        to.setAttribute("value", from.getAttribute("value"));
    }
}
<body>
    <!-- The non-submitted form, for the radio buttons. -->
    <form id="start_form" name="start_form" action="nowhere.php" method="post">
        <input type="radio" name="start" value="First" onchange="copyValue(this, 'start_hidden');">First<br>
        <input type="radio" name="start" value="Second" onchange="copyValue(this, 'start_hidden');">Second<br>
        <input type="radio" name="start" value="Third" onchange="copyValue(this, 'start_hidden');">Third<br>
    </form>
    
    <!-- The form that gets submitted; the one with the hidden, copied value -->
    <form id="theForm" action="?" method="post">
        <input type="text" name="SomethingVisible">
        <input type="hidden" name="start_value" id="start_hidden" value="none">
        <input type="submit">
    </form>
</body>
0

Ok I think I understand now. You are trying to do something similar to what is often called a dependent drop-down, where changes done to one field in a form updates the contents of another.

There are a few ways to handle that. The simplest is to just submit the form after each input is altered, each time updating the form as needed, but never actually processing the data until after all the fields have been selected. (You would use PHP to validate the input and simply re-display the form if something is missing.)

However, a more elegant way is to use JavaScript and AJAX to fetch the data you need, and update the form without refreshing the page. This makes it a LOT more attractive to the user.

I don't know exactly the data you are working with, but let me give you a generic example. (You can see it in action on my test server )
(Note that this example will not work unaltered in most versions of IE (IE 8 should be fined though). I recommend Firefox with the Firebug extension, so you can see exactly what is going on.

Say you have this data in a MySQL database:

And you wanted to display radio button for each category, which when selected, would allow you to select one of it's products from a select box.

You could start with an index page like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
    <title>Dynamic Input Example, using AJAX</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="scripts.js"></script>
    <link rel="stylesheet" type="text/css" media="all" href="main.css">
</head>
<body>
    <form id="criteria_form" action="process.php" method="post">
        <h1>Category:</h1>
        <ul>
            <!-- This is static, but you could have PHP insert this
                 dynamicall if you wanted to. -->
            <li><input type="radio" name="start" value="Bikes">Bikes</li>
            <li><input type="radio" name="start" value="Cars">Cars</li>
            <li><input type="radio" name="start" value="Mobile Phones">Mobile Phones</li>
        </ul>

        <h1>Items:</h1>
        <select name="items" id="items">
            <option value="null">-- Please select criteria --</option>
        </select>
        
        <input type="submit">
    </form>
</body>
</html>


There is nothing really special in that code, as you can see. All the "magic" happens in the script file, which is included into the page in the header.

/**
 * This is the code that is executed when the page has been loaded.
 * It simply sets the "onchange" event callback for all the radio
 * boxes, so they will update the select box when selected.
 */
window.onload = function() {
    var rbuttons = document.getElementsByName("start");
    if(rbuttons.length > 0)
    {
        for(var i = 0; i <  rbuttons.length; i++) 
        {
            rbuttons[i].onchange = criteriaOnChange;
        }
    }
}

/**
 * This is what is called when a radio button is selected. It sends
 * a request, via AJAX, to the PHP file, which returns all the items
 * for the category that is selected.
 */
function criteriaOnChange() {
    // The "this" keyword referrs to radio box itself, so this
    // fetches the value we give it in the HTML
    var categoryName = this.value;

    // This is the URL where the PHP script is. Note that I add the
    // category name to the query string, so PHP can read it.
    var getUrl = "getItems.php?category=" + encodeURIComponent(categoryName);

    // Create an AJAX request. If you want this to be compatible with
    // older version of IE (IE 7 and older, I believe) you need to
    // use the  ActiveX object here when appropriate.
    var ajax = new XMLHttpRequest();

    // The code that is called when the response is received.
    ajax.onreadystatechange = function()
    {
        if(ajax.readyState == 4) // 4 == response ready
        {
            if(ajax.status == 200) // 200 == success!
            {
                // The PHP code returns the data as a JSON object,
                // which means I can simply execute it as JavaScript
                // code and assign the values to a local variable.
                eval("var items = " + ajax.responseText);
                // NOTE! This eval function not the most secure of methods.
                // See the following blog for details on how to improve this:
                // - http://socket7.net/article/how-to-safely-parse-json

                // Get the select box where the items are listed.
                var select = document.getElementById('items');

                // Clear all the previous items from it.
                while(select.options.length > 0) {
                    select.options[0] = null;
                }

                // Add all the new items to the box.
                for(var i = 0; i < items.length; i++) {
                    select.options.add(new Option(items[i], items[i]));
                }
            }
            else {
                // The response failed for some reason.
                alert("AJAX failiure. Code: " + ajax.status);
            }
        }
    }

    // Send the request.
    ajax.open('GET', getUrl, true);
    ajax.send(null);
}


The PHP code the AJAX request calls could be as follows:

<?php
// We are sending this to JavaScript, so return this as a JSON
// object. (JSON = JavaScript Object Notation)
header('Content-type: application/json; charset=UTF-8');

// Connect to MySQL. Note that I use the improved MySQL extension.
// You can replace this with the old MySQL functions if you want.
$dbLink = new mysqli('localhost', 'user', 'pass', 'dbName');
if(mysqli_connect_errno()) {
    die("Failed to connect to MySQL: " . mysqli_connect_error());
}

// Try to get the category named passed from the JavaScript code.
// If it fails, return an error message.
if(!isset($_GET['category'])) {
    echo json_encode(array(
        'error' => 400,
        'message' => 'No category name was passed.'
    ));
    exit;
}
else {
    $categoryName = $dbLink->escape_string($_GET['category']);
}

// Query the items for the selected product from the database.
$sql = "SELECT `product_name`
        FROM `product_table`
        WHERE `category_name` = '{$categoryName}'";
$result = $dbLink->query($sql);

// See if the query returned any items. If not, send an appropriate
// error message.
if(!$result) {
    echo json_encode(array(
        'error' => 500,
        'message' => 'MySQL error: ' . $dbLink->error
    ));
    exit;
}
else if($result->num_rows == 0) {
    echo json_encode(array(
        'error' => 404,
        'message' => 'The requested category has no items.'
    ));
    exit;
}

// Create an array of the items returned by MySQL.
$items = array();
while($row = $result->fetch_assoc())
{
    $items[] = $row['product_name'];
}

// Turn the array into a JSON object and print it.
echo json_encode($items);

// Clean up.
@$result->close();
@$dbLink->close();
?>


Then, once you have chosen a category, selected an item and submitted the form ,the process.php page would receive it and do whatever it is you want done with it. To simply see the data, you could do:

<?php
echo "<pre>", print_r($_POST, true), "</pre>";
?>


I hope this helps point you in the right direction, at least.

Edited by Atli: n/a

Attachments pc.png 6.93 KB
0

Hi ajwei810192 ,

<input type="hidden" name="form2" value="<?php echo 'test'?>"/>

If I given like above its working, means it passed the value and displayed it. Nothing error in your code, the value of $start and $end is not retrieved there.

You should retrieve the value of start and end as

$start=$_POST['start'];
$end=$_POST['end'];
0

Ali and rajarajan07,

The part that you are talking about here that I may have issues with, the values on my dependent drop down is displaying properly, and if I really want to pass the values to the second page saying what value I select, such as apartment, drugstore or others, I can get it displayed. The problem I am having is how to pass the values of the dependent drop down to another form.

Say ,that I select Drugstore, and it gives me CVS East, I would like to pass that to process.php from my form. For some reason, when I wanted to do that, it does not pass that in, and obviously using $form2 as a hidden value to pass things is not passing any. I only get a blank.

I am wondering if it is possible that you may be able to help me by providing a simple example on the similar problem. or if you could tell me how I could get that value passed in.

Is what I am talking about here possible? I guess that there must be a mistake in what I put for my input hidden, am I right?

Thanks for your help.

0

Hey,
1. Whether both these forms were in the same page?
2. How you r getting value for $start?
3. Just take "View Source" and find whether

<input type="hidden" name="form1" value="<?php echo $start?>"/>

$start value is actually present or not?

0

Hey,
1. Whether both these forms were in the same page?
2. How you r getting value for $start?
3. Just take "View Source" and find whether

<input type="hidden" name="form1" value="<?php echo $start?>"/>

$start value is actually present or not?

No, I never see $start, since once I push on the drop down menu, the check function takes care of it by bringing me the drop down menus, and here is the code for my check function,

function check(field)
{
  var str ="";
  for (i=0;i<field.length;i++)
  if (field[i].checked==true) str = field[i].value + " ";  
  start_menu();
  var url = "test_getrss.php?q=" + str;
  xmlhttp.open("GET",url,true);
  xmlhttp.send();
  
}

function start_menu() {

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200){
    document.getElementById("start_menu").innerHTML=xmlhttp.responseText
    }  
  if(xmlhttp.responseText == " ") alert("Unable to process request");
  }
}

And, this is what I have for my process.php

<?php

$form1 = $_POST['form1'];
echo "Start Location " . $form1 . "<br />";

?>

I get nothing other than the string that I have hard coded in. And this is what is in my test_getrss.php:

<?php
//get the q parameter from URL
// Make a MySQL Connection
mysql_connect("localhost", "xxx", "xxxxxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$q=$_GET["q"];

$query="SELECT test FROM test_from WHERE type='" . $q . "'";
//find out which feed was selected
$result = mysql_query ($query);
echo "<select name='start'>";
// printing the list box select command

while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value=$nt[0]>$nt[0]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box 
?>

As you can see, the result is generated still with the name "start", and yet not the same as the original. However, looks like when I select the items generated from this menu, they cannot yet be passed to process.php, which is a different page. When I can get this function to work, then maybe I would reconsider putting all on one page.

For some reason, I cannot pass all the parameters on as I like. If there is a way that I can put the request of fetching the dependent select menu on the first page, without my having to fetch the dependent select on a different page other than what the form started out with, that would be great.

I hope I am making sense here what I am trying to do.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.