THE ISSUE?
I need help regarding PHP's onChange command. Basically i'm making a hotel room reservation system. What im trying to do is that there are tow combo boxes.
One for HOTEL NAME (COMBO BOX NO.1)
the other for FLOOR NO (COMBO BOX NO.2)
What I want to do is that if I select the hotel name form the combo box 1, then the number of floors for that particular hotel, should get auto-populated in combo box 2. (This number of floors information should come from the respective table/field in the database)
WHAT i'VE TRIED TO DO -- THE CODE
<td>Hotel:
<select name="hotel_name" id="hotel_name" title="<?php echo $row_rs_hotel['hotel_name']; ?>" onchange="<?php
while ($row_rs_floor = mysql_fetch_assoc($rs_floor));
$rows = mysql_num_rows($rs_floor);
if($rows > 0) {
mysql_data_seek($rs_floor, 0);
$row_rs_floor = mysql_fetch_assoc($rs_floor);
}
?>">
<?php
do {
?>
<option value="<?php echo $row_rs_hotel['hotel_name']?>"><?php echo $row_rs_hotel['hotel_name']?></option>
<?php
} while ($row_rs_hotel = mysql_fetch_assoc($rs_hotel));
$rows = mysql_num_rows($rs_hotel);
if($rows > 0) {
mysql_data_seek($rs_hotel, 0);
$row_rs_hotel = mysql_fetch_assoc($rs_hotel);
}
?>
</select></td>
</tr>
<tr>
<td>Floor No:
<select name="floor_no" id="floor_no" title="<?php echo $row_rs_floor['floor_no']; ?>" onchange="var id=$('hotels_name').val();
$('floors_no').load('ajax.php?id='+id);
">
<?php
do {
?>
<option value="<?php echo $row_rs_floor['floor_no']?>"><?php echo enter code here$row_rs_floor['floor_no']?></option>
<?php
} while ($row_rs_floor = mysql_fetch_assoc($rs_floor));
$rows = mysql_num_rows($rs_floor);
if($rows > 0) {
mysql_data_seek($rs_floor, 0);
$row_rs_floor = mysql_fetch_assoc($rs_floor);
}
?>
</select></td>
WHAT I'M GETTING FROM THE ABOVE CODE??
The combo box number 2 is auto-loaded with the first record in the table when the page is opened. No matter how many times i select the hotel in COMBO BOX 1, the values in combo box 2 remain unchanged.
PLEASE HELP..!!!
You must combine both javascript and php, as you want to retrieve the information from the database (server side using php+a bit of mysql) with a dynamic page without refresh (client side using javascript). It will certainly become a long difficult job, but I think it's the best approach.
Read this article about double drop down menu and study the code this article (or search for similar projects) and when you understand the javascript, you must fill it where it's appropriate with php.
For example, this is a bit of the javascript (or html) source code:
if (Indx==1)
{
options[0]=new Option("Choose a JavaScript Page","");
options[1]=new Option("Alerts","alerts.htm");
options[2]=new Option("Back and Forward Buttons","BackForward.htm");
options[3]=new Option("Contents","index.html");
}
For your project it should be something like this (not complete and not bug-free, but it's just to give you an idea:
if (Indx==1)
{
<?php
$i=0;
while ($row = mysql_fetch_array($result))
{
?>
options[<?php echo $i;?>]=new Option("<?php echo $row['name']."\",\"".$row['page']; ?>");
<?php $i=$i+1; } ?>
}
That should give you the same code (assuming that 'name' and 'page' are values of your columns in your database). And that needs to be done in all convenient javascript bits, but I won't do all your work... give it your best and, if it still doesn't work, come back and ask a more specific question about the code.
If you make it work, I'd like to encourage you to post it here editing your question so everyone can learn from it. Keep in mind that this is how I would approach this problem, but there are surely other ways of doing it.
Related
This is a bit hard for me to explain and I don't really have any examples to show as I don't know how to do it.
What I am trying to do is to have fields automatically filled up for me based on my selection which is taken from my database.
Let's say I'm trying to fill data up for a casualties form and I'm getting my selection for my fields from a people's database and that database contains all the information of everybody inside, information such as the contact number, next of kin, full name, their IC etc etc.
Is there a way to display data such contact number, next of kin, IC number based on let's say their name inside the form itself?
$query = "SELECT * FROM staff";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
.... in the form itself
<tr>
<td><label><b>Staff ID</b></label></td>
<td><select name="staffID"><option value="">Select staff ID</option>
<?php
while ($row = mysqli_fetch_assoc($result)) {
?>
<option value="<?php echo $row['staff_id']; ?>">
<?php echo $row['staff_id']; ?>
</option>
<?php } ?>
</select></td>
</tr>
The idea is, after they selected an ID from the dropdown box, additional fields will appear, giving the user more details of the staff such as their full name, contact number etc etc.
I can echo out all their ID and I know how to generate out additional fields but I don't know how to auto fill up data on those fields based on the staff_ID they selected.
Sorry if this is confusing, english is not my main language and I'm pretty terrible with programming
English is not my natural language (i`m from brazil).
In this case you will need to use AJAX. The easier way to do that is using Jquery (www.jquery.com). I will put here the easier way, but if cant help, tell me again.
---Let`s go --------------
<option id="reportedBy" name="reportedBy">
<option value="staff" data-name="Full Name of Staff" data-no="(222)2222-2222">
</option>
So you will make a script using jquery. When this option change his value, you will get the selected option value and get the others data using the dataset.
<script>
$(document).ready(function(){
$("#reportedBy").change(function(){
name = $(this).find(":selected").data("name"); //data-name less data-
no = $(this).find(":selected").data("no"); //data-no less data-
//Assuming your textfilds use the id "name" and no
$("#name").val(name);
$("#no").val(no);
});
});
</script>
Thanks for taking time to look at this.
I have two drop down menus. The first is a list of clients, the second is a list of projects.
All projects are tied to just one client, so I'd like for the code to get user input for the client, then read that value, and modify the PHP code to only print out the values in the second drop down menu that correspond to the client selected.
Here's some code. For the first drop down menu:
<div class="item">
<label for='clSel' id='tsClLabel'>Client:</label>
<select name='clSel' id='wClient' onChange="bGroup();">
<option></option>
<?php
$cQuery = "SELECT * FROM Clients ORDER BY Client_Name";
$cResult = mysql_query($cQuery);
while($cData = mysql_fetch_assoc($cResult)) {
echo '<option id="Cid" value="'.$cData['Id'].'">'.$cData['Client_Name'].'</option>';
}
?>
</select>
Here's my jQuery function to get the user-selected value from the first drop down:
<script>
function bGroup(){
val1 = $("#wClient").val();
// window.alert(val1);
// $('#div1').html(val1);
return val1;
}
</script>
And the code for the second drop down menu:
<label for='billGroupId'>Billing Group: </label>
<select name='billGroupId'>
<option value=''></option>
<?php
$sql = "SELECT * FROM Billing_Groups ORDER BY Client_Id, Name";
$sth=$dbh->prepare($sql);
$sth->execute();
while ($row = $sth->fetch())
{
if ($row['Name']!= ''){
echo "<option value='".$row['Id']."' > ".$row['Name']."</option>";
echo "<script> bGroup(); </script>"
}
}
?>
</select>
I know I need to include a WHERE statement in the second drop down menu
Basically Select * FROM Clients WHERE Client_ID == $jsVAR.
I already have the value I need in the var1 JavaScript variable. How can I get this little piece of data either read by PHP or sent to PHP via JS code?
Thanks!!
You can SELECT all records from the database, and then insert them to your page HTML using json_encode(). Something like that:
<?php
$sql = "SELECT * FROM Billing_Groups ORDER BY Client_Id, Name";
$sth=$dbh->prepare($sql);
$sth->execute();
$projectData = array();
while ($row = $sth->fetch())
{
if ($row['Name']!= ''){
$projectData[$row['Client_Id']][] = $row;
}
}
echo '<script type="text/javascript">var projects=', json_encode($projectData), ';</script>';
?>
Then, in your JS, you use the variable projects as an associative array (object), eg.:
<script type="text/javascript">
for (p in projects[clientId]) {
alert(projects[p].Name);
}
</script>
Tricky one,
You have a choice. One way is to use Ajax to grab the second level menu structure upon getting the first level choice, and populate the second level once that succeeds. That's likely to be a problem, as there will likely be some sort of network delay while that happens, of which you have no control (unless you are in a closed environment). So from a user point of view it could be counter intuitive and sluggish feeling, especially on a slow connection or shared hosting solution where timings can vary enormously.
The other way is to somehow pull all values possible and filter them (so hide the ones that don't apply) using jQuery, perhaps utilising classes or some other attribute as a method of filtering data. Using jQuery you can assign data to elements so you could also use that too. The second method may not be so good if there's a lot of data (can't tell from the scenario you've described). Looking at your second level code I don't see a WHERE condition so I'm not sure how the value from the first level is affecting that of the second level, so it's hard to know how to deal with that for this method.
I'm bug-proofing a form that allows data editing for book entries in a database. Everything is working except for the drop-down box. The drop-down box automatically populates itself with every unique entry in a specific field in the database table, and that part works perfectly. However, when people click to edit a book all the fields are populated with that books information, and I wanted the drop-down box to default to the correct value for that book. My solution was to check each value as it populates the drop-down box against the actual book's value for that field and if they match, make it the "selected" value.
It is not working. The box is still populating fine, but it is not defaulting. Here is the code for the drop-down box.
<span style="margin-left:10px;">
Publication Type:
<select name="publicationType" >
<option value=""></option>
<option value="">-------------------------</option>
<?php
$lPub = '';
if(array_key_exists('publicationType',$_REQUEST)) $lPub = $_REQUEST['publicationType'];
$lPubArr = $datasetManager->getPublicationType();
foreach($lPubArr as $pubStr){
if($pubStr == $bookArr['publicationType']){
echo '<option '.($lPub==$pubStr?'selected="selected"':'').'>'.$pubStr.'</option>'."\n";
}
else{
echo '<option '.($lPub==$pubStr?'':'').'>'.$pubStr.'</option>'."\n";
}
}
?>
</select>
</span>
I can provide what all the variables are if needed. I don't see what I'm doing wrong, but maybe someone will be able to catch an obvious mistake.
Thank you,
Kai
Not sure this will help but try this:
<?php
$lPub = '';
if( array_key_exists('publicationType',$_REQUEST) )
$lPub = $_REQUEST['publicationType'];
$lPubArr = $datasetManager->getPublicationType();
foreach($lPubArr as $pubStr){
echo '<option '.($lPub==$pubStr?'selected="selected"':'').'>'.$pubStr.'</option>'."\n";
}
I removed this condition:
f($pubStr == $bookArr['publicationType'])
since I didn't get what the $bookArr['publicationType'] is used for, perhaps you left it there by mistake
I have written the following code in PHP to generate two dropdown boxes on the same page.
The first dropdown box gets value from a MySQL table. This dropdpwn box contains some UserIDs. The second dropdown box contains some dates which should be based on the UserID that is selected in the first dropdown box. I have filled the 2nd dropdown box with all the dates in the MySQL table, but, it should be filtered by the UserID which is selected on the first dropdown box.
Just to inform, with these two values from these two dropdown boxes in this PHP page, I have posted them by pressing the submit button to another PHP page to process some other work.
I would appreciate if you can help me to fill the second dropbox only based on the UserID selected on the first dropbox. Here is the code I have written to display and fill those dropdown boxes. Can you please inform me, what part of the code I should modify and I would appreciate if you can show me the modification code as well. I am a newbie in PHP, that's why I am asking for code level help.
My code:
<html>
<head>
<title>
Search Alert DB
</title>
<body>
<br />
<?php>
$con = mysql_connect("localhost","root","root"); // (host, user,pwd)
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mysql", $con);
echo "<p> Search Alert database </p>";
echo "<br />";
$result = mysql_query("SELECT distinct(UserID) FROM tblAlertLogSpecificUsersDayStatusFinal_1");
$options="";
echo "<form action='Search_AlertDB_process.php' method='POST'>\n";
//echo "Please choose a user: ";
echo "Please choose a user: <select name = userid>";
echo "<option>-Select-";
while ($row = mysql_fetch_array($result))
{
$userid=$row["UserID"];
$options ="<option value = \"$userid\">$userid </option>";
echo "$options";
}
echo "</select>";
echo "<br />";
echo "<br />";
$dayresult = mysql_query("SELECT distinct(Occurred_date) FROM tblAlertLogSpecificUsersDayStatusFinal_1");
$dayoptions="";
echo "Please pick a date:<select name = day>";
echo "<option>-Select-";
while ($row=mysql_fetch_array($dayresult)) {
$day=$row["Occurred_date"];
$dayoptions ="<option value = \"$day\">$day </option>";
echo "$dayoptions";
//$options.="<OPTION VALUE=\"$id\">".$day;
}
echo "</select>";
echo "<br />";
mysql_close($con);
?>
<br />
<input type="submit" name="Submit" value="Search" /> <br /> <br />
</form>
</body>
</html>
You'll need 3 things
Initial page with select fields
The first select field is pre-populated with user ids
The second field contains no options and is disabled
A separate endpoint/page that takes a user id as a parameter to return relevant dates
It should probably return JSON/XML (or something similar), or you could return the dates pre-rendered in <option /> tags (shouldn't really do this, but it would be quicker to hack this together)
Javascript callback triggered when an option in the first dropdown is selected. The callback should send an AJAX request to the separate endpoint and populate the second dropdown with the result.
It would have probably been easier for me to write it all out for you than [try] to explain it, but that's not really the point. Just trying to set this all up (all be it; relatively simple) will teach you a whole load of things about Javascript, AJAX and web services.
If you choose to return JSON/XML from your web service (the separate endpoint/page), and hopefully you will, you might also start to see the benefit of separating logic from presentation, which will make the world of difference to both your understanding and delivery of code.
Well, we wont write the code for you. Otherwise you are going to be newbie for all your life :)
What you need here is called AJAX. The easiest way to implement it is probably jQuery ajax function. If you don't know jQuery - learn the basics, it shouldn't take more than an hour or so. It's worth it :)
I am not exactly how to do it and how to word the question, so i shall try my best (PS: i'm new to web dev, so please be clear in your answers if you could).
So, I have got a drop down menu with the list names, which are taken from my database. In that database i have a table with names column (the ones that are rendered to the dropdown box) and relevant information to those names. Now, I want that relevant information to appear below in a tag when a user choose one of those names. I also cannot use the form.submit() method because my submit button is already taken for something else.
Here is the code to that bit:
<form name="name_choice" method="post" action="index.php">
<select name="names" onchange="form.some_method()">
<option value="NULL" selected="selected">--Select name--</option>
<?php
for ( $i = 0; $i < $numrows; $i++ ) { //for all the columns, iterate and print out
$id_names = mysql_result($result, $i);
echo "<option value='".$id_names."'>".$id_names."</option>";
}
?>
</select>
</form>
So the bit above works fine, but the "some_method()" is my problem, i don't know what to trigger to display the text in the div below the drop down box (code is below for it):
<div class="information"> <!--if the name is chosen ONLY!-->
<?php
if($_POST['names'] == "NULL") {
echo '<p>Please select an option from the select box.</p>'; //this bit is for testing
}
else {
echo '<p>You have selected: <strong>', $_POST['names'], '</strong>.</p>';
//and then how to echo the relevant information?:(
}
?>
</div><!--end of possible info-->
onchange is a JavaScript event. PHP can't do realtime processing of form data, as it sits on the server and the form is on the client. You can sort of do it by using AJAX and passing the form data as the user types, but that would be a lot more work than is needed. Take a look at JavaScript form validation posts to get yourself headed on the correct path.