How do I selectively add 3rd select box or relabel & redirect to a 2nd select box? - php

I have a form where the 1st select box is required. Depending on the selection, a different table will be used as a source for the query to populate a 2nd select box. Then depending also on the 1st selection a 3rd select box may or may not be necessary. I have designed the form to initially show 3 select boxes, but the user would have to know to skip the 2nd select box in some cases. This is confusing at the least. As an example:
If None is selected for Company, then both the Cemetery & Section select boxes would have to shown (Section being dependent on Cemetery selected). If XYZ Company is selected, then only the Section select box would need to be seen / selected (as the Cemetery is Company specific):
<script>
function getCemetery(val) {
$.ajax({
type: "POST",
url: "get_cemetery.php",
data:'company_name='+val,
success: function(data){
$("#cemetery-list").html(data);
}
});
}
Here is the code of the form:
<body>
<div class="frmDronpDown">
<div class="row">
<label>Company:</label><br/>
<select name="company" id="company-list" class="demoInputBox" onChange="getCemetery(this.value);">
<option value="">Select Company</option>
<?php
foreach($results as $company) {
?>
<option value="<?php echo $company["name"]; ?>"><?php echo $company["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>Cemetery:</label><br/>
<select name="cemetery" id="cemetery-list" class="demoInputBox" onChange="getSection(this.value);">
<option value="">Select Cemetery</option>
<?php
foreach($results as $cemetery) {
?>
<option value="<?php echo $cemetery["name"]; ?>"><?php echo $cemetery["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>Section:</label><br/>
<select name="section" id="section-list" class="demoInputBox">
<option value="">Select Section</option>
</select>
</div>
</div>
</body>
And here is the additional php code the is called within the script:
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["company_name"])) {
if (($_POST["company_name"]<>"None") && ($_POST["company_name"]<>"Other")) {
$sql="SELECT name, available FROM compsections WHERE cname = '".$_POST["company_name"]."'"." ORDER by available desc;";
$result = mysql_query($sql) or die ( mysql_error());
$row = mysql_fetch_row($result);
$section = $row[0]; // best choice to use if auto fill
$query="SELECT * FROM compsections WHERE cname = '".$_POST["company_name"]."'"." ORDER by available desc;";
$results = $db_handle->runQuery($query);
echo '<option value="">Select Section</option>';
}else{
$query ="SELECT * FROM cemeteries";
$results = $db_handle->runQuery($query);
echo '<option value="">Select Cemetery</option>';
}
foreach($results as $cemetery) {
?>
<option value="<?php echo $cemetery["name"]; ?>"><?php echo $cemetery["name"]." - ".$cemetery["available"]; ?></option>
<?php
}
}
?>
Edit:
Thank you for telling me about .hide and .show. I have looked up examples and what I can find uses a button click. Would you show an example of using them in an php if..else?
Thank you in advance.
Russ

I used the following:
<script>
function wholesection() {
$( "#whole-section" ).slideUp( "fast", function() {
});
}
</script>
AND
echo '<script>',
'wholesection();',
'</script>'
;

Related

Inserting values into database from form with drop downs

I'm trying to insert values input from the user in a form into my database.
I am trying to create 2 drop down lists, with the first deriving the options for the second. For example the first drop down list for Faculty, with the second drop-down list containing the schools within the selected faculty.
I am also then wanting to insert the gathered information into my database however I can focus on that after getting the drop-down's correct first.
My register page is on one page with the getSchool.php on a different file, I have a feeling the connection between the two could be my issue.
The register.php is below. This is the page the form is on
<?php
session_start();
include('dbConnect.php');
$queryStr=("SELECT * FROM faculty");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<html>
<head>
<TITLE>Faculty & School</TITLE>
<head>
<!-- Help for code to create dynamic drop downs -->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"
type="text/javascript"></script>
<script>
function getFaculty(val) {
$.ajax({
type: "POST",
url: "getFaculty.php",
data:'facultyID='+val,
success: function(data){
$("#schoolList").html(data);
}
});
}
function selectFaculty(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
</script>
</head>
<body>
<div class="frmDronpDown">
<div class="row">
<label>Faculty:</label><br/>
<select name="faculty" id="facultyList" class="demoInputBox"
onChange="getFaculty(this.value);">
<option value="">Select Faculty</option>
<?php
foreach($results as $faculty) {
?>
<option value="<?php echo $faculty["facultyID"]; ?>"><?php echo
$faculty["facultyName"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<form action="addBlood.php" method="post">
<label>Test:</label><br/>
<select name="test" id="test-list" class="demoInputBox">
<option value="">Select Test</option>
</select>
</div>
</div>
<label>Result:</label><input class="input" name="result" type="text"><br>
<label>Date:</label><input class="input" name="date" type="date"><br>
<input class="submit" name="submit" type="submit" value="Submit">
</form>
Below is the getSchool.php which gets all the schools
<?php
include('dbConnect.php');
if(!empty($_POST["facultyID"])) {
$queryStr=("SELECT * FROM school WHERE facultyID = '" . $_POST["facultyID"]
. "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<option value="">Select School</option>
<?php
foreach($results as $school) {
?>
<option value="<?php echo $school["schoolID"]; ?>"><?php echo
$school["schoolName"]; ?></option>
<?php
}
}
?>
Thanks in advance for any feedback and help.
Simon
url: "getFaculty.php",
data:'facultyID='+val,
success: function(data){
$("#schoolList").html(data);
Where is the #schoolList element ? Why getFaculty.php? Should it not be getSchool.php ?
First, just to re-iterate what was already mentioned, update your getFaculty() to get getSchool() and make sure it points to getSchool.php.
Now, you need to create a div following your first drop-down with an id schoolList.
<div class="row" id="schoolList"></div>
Now, update your getSchool.php so that it generates the full form/selection. Something along the lines of:
<?php
include('dbConnect.php');
if(!empty($_POST["facultyID"])) {
$queryStr=("SELECT * FROM school WHERE facultyID = '" . $_POST["facultyID"]
. "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<label>Schools:</label><br/>
<select name="schoolSelect" id="schoolSelect" class="demoInputBox">
<option value="">Select School</option>
<?php
foreach($results as $school) {
?>
<option value="<?php echo $school["schoolID"]; ?>"><?php echo
$school["schoolName"]; ?></option>
Once you've got those ideas down, you'll have to make sure you have the full flow of your page the way you want it. Then follow similar standards for posting any inputs to the php page you use for database manipulation.
As noted in earlier posts, this solution still leaves you vulnerable to injection. That's for another post, another day.

Dynamic Dependent Dropdown

I have a form that pulls some dropdown data from an existing db. I've been working on a second dropdown that references the first to get more specific information from a different DB, however it looks like my code is broken somewhere. The first dropdown is populated fine but when i choose a "Manager" the Site dropdown goes blank, I even lose the "Select Site" option.
Any help would be appreciated.
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function getSite(val) {
$.ajax({
type: "POST",
url:"get_site.php",
data:'manager_id='+val,
success: function(data){
$("#site-list").html(data);
}
});
}
</script>
html/php
Manager<br/>
<select name="manager_id" onChange="getSite(this.value);">
<option value="">Select Manager</option>
<?php
$results = mysql_query("SELECT * FROM _managers");
while ($row_unit = mysql_fetch_array($results)){
?>
<option value="<?php echo $row_unit["id"]; ?>"><?php echo $row_unit["company"]; ?></option>
<?php
}
?>
</select>
<br/><br/>
Site<br/>
<select name="site_id" id="site-list">
<option value="">Select Site</option>
</select>
get_site.php
<?php
include('includes/connect-db.php');
if(!empty($_POST["manager_id"])) {
$manager_id = $_POST["manager_id"];
$results = mysql_query("SELECT * FROM _sites WHERE manager_id = $manager_id");
?>
<option value="">Select Site</option>
<?php
while ($row_site = mysql_fetch_array($results)){
?>
<option value="<?php echo $row_site["id"]; ?>"><?php echo $row_site["site_name"]; ?></option>
<?php
}
}
?>
As per discussion in comment.
I made the adjustment but still not getting my values from the
"get_site.php" file. Although now the "Select Site" stays in the site
dropdown.
Assuming you are getting proper data from MySQL server do some changes in get_site.php as below.
get_site.php
<?
include 'includes/connect-db.php';
if ((!empty($_POST["manager_id"])) && (isset($_POST["manager_id"])))
{
$manager_id = $_POST["manager_id"];
$results = mysql_query("SELECT * FROM _sites WHERE manager_id = '{$manager_id}'");
$options = "<option value=''>Select Site</option>";
while ($row_site = mysql_fetch_assoc($results))
{
$options .= "<option value='{$row_site['id']}''>{$row_site['site_name']}</option>";
}
return $options; // I personally prefer to echo using json_encode and decode it in jQuery
}
?>
Above code should give you the data you want.
Hope this solves your issue.Do comment if you are having any difficulties.

Empty query result

in a web form there are two drop-down lists. The second list items should change dynamically depending on the value selected on the first drop-down list.
This is how am I trying to do it:
index.php:
...
<script>
function getClient(val) {
$.ajax({
type: "POST",
url: "get_contacts.php",
data:'client_id='+val,
success: function(data){
$("#contacts-list").html(data);
}
});
}
</script>
...
<div class="form-group">
<label for="mto_client" class="col-sm-2 control-label">MTO Client</label>
<div class="col-sm-10">
<select name="mto_client" id="clients_list" onChange="getClient(this.value)">
<option value="">Select a Client</option>
<?php
do {
?>
<option value="<?php echo $row_RSClients['id_client']?>" ><?php echo $row_RSClients['client_name']?></option>
<?php
} while ($row_RSClients = mysql_fetch_assoc($RSClients));
?>
</select>
</div>
</div>
<div class="form-group">
<label for="mto_client_contact" class="col-sm-2 control-label">MTO Client Contact</label>
<div class="col-sm-10">
<select name="state" id="contacts-list">
<option value="">Select Client Contact</option>
</select>
</div>
</div>
get_contacts.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["client_id"])) {
$query ="SELECT * FROM tb_client_contacts WHERE contact_client_id = '" . $_POST["client_id"] . "'";
$results = $db_handle->runQuery($query);
?>
<option value="">Select Client Contact</option>
<?php
foreach($results as $state) {
?>
<option value="<?php echo $state["id_client_contact"]; ?>"><?php echo $state["contact_name"]; ?></option>
<?php
}
}
?>
There are objects on the table tb_clients_contact that meet the condition, but the second drop-down list doesn't show any objects.
Any help is welcome.
Instead of
$("#contacts-list").html(data);
It should be
$('#contacts-list').empty().append(data);
empty() will clear first the options inside the contacts-list select field, then append() will insert the options from the result of your AJAX.
You can also look at the console log for errors. If you are using Google Chrome, hit F12 to display the console log.

Show/hide select values based on previous select choice

I have 2 select's inside a form. The second select has about 2000 lines in total coming out of my mysql table. One of the column into that mysql has 1 of the values used into the first select. I want to be able to filter on that value when it is selected into the first select, so that it only shows these articles.
code now:
<div class="rmaform">
<select name="discipline" class="discipline">
<option value=" " selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article">
<?php
$articleselect = $dbh->prepare('SELECT * FROM articles');
$articleselect->execute();
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
</select>
I think i have to use Javascript for it but how do you combine PHP and Javascript? And what would be the best way to make the filter work?
jQuery for the change event and AJAX
$(document).ready(function(e) {
$('select.discipline').change(function(e) { // When the select is changed
var sel_value=$(this).val(); // Get the chosen value
$.ajax(
{
type: "POST",
url: "ajax.php", // The new PHP page which will get the option value, process it and return the possible options for second select
data: {selected_option: sel_value}, // Send the slected option to the PHP page
dataType:"HTML",
success: function(data)
{
$('select.input-article').append(data); // Append the possible values to the second select
}
});
});
});
In your AJAX.php
<?php
if(isset($_POST['selected_option']))
$selected_option=filter_input(INPUT_POST, "selected_option", FILTER_SANITIZE_STRING);
else exit(); // No value is sent
$query="SELECT * FROM articles WHERE discipline='$selected_option'"; // Just an example. Build the query as per your logic
// Process your query
$options="";
while($query->fetch()) // For simplicity. Proceed with your PDO
{
$options.="<option value='option_value'>Text for the Option</option>"; // Where option_value will be the value for you option and Text for the Option is the text displayed for the particular option
}
echo $options;
?>
Note: You can also use JSON instead of HTML for much simplicity. Read here, how to.
First give both of the selects an unique ids...
<div class="rmaform">
<select name="discipline" class="discipline" id="discipline">
<option value="" selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article" id="article">
<option value="" selected></option>
</select>
Now you can use jQuery Ajax call to another file and get the HTML Response from that file and Populate in the select field with id="article" like this...
<script type="text/javascript">
$(document).ready(function(){
$("#discipline").change(function(){
var discipline = $(this).val();
$.post(
"ajax_load_articles.php",
{discipline : discipline},
function(data){
$("#article").html(data);
}
)
});
});
</script>
Now create a new file like ajax_load_articles.php... in the same directory where the html file exists... You can place it anywhere but then you have to change the $.post("url", the url to the ajax submission.
Contents of ajax_load_articles.php :
<?php
$discipline = $_POST["discipline"];
$articleselect = $dbh->prepare("SELECT * FROM articles WHERE colname = '{$discipline}'");
$articleselect->execute();
echo '<option value="" selected></option>';
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
Now when ever you will change the select of the first select field an Ajax call will take place and the data of the second select field will automatically adjust to related data selected in the first select field.
This is an example where you can select the college specific to the state ..
Form.php
// your code for form ...
// select box for state starts
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">State</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="statename" id="stateid">
<option value="">---- Select ----</option>
<?php
$state=sql::readResultArray("Your Query To select State`");
foreach($state as $s){
?>
<option value="<?php echo $s?>"> <?php echo $s ?> </option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">Colleges</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="mycollegename">
<option value="">--- Select --- </option>
</select>
</div>
</div>
// further code for from in form.php..
Script to find the state and then pass the value to find the respective colleges in that state
<script>
$(document).ready(function(e) {
$('#stateid').change(function()
{ ids=$('#stateid').val();
$.get('mycollege.php', {type:ids} ,function(msg){
$('select[name="mycollegename"]').html(msg);
});
});
});
</script>
Call this file through ajax .. Code on this file
mycollege.php
<?php
require('db.php'); // call all function required, db files or any crud files
$type=$_GET['type'];
if(!empty($type)){
$r=sql::read("Your Query To call all teh college list");
?>
<select name="mycollegename">
<option value="">Select One</option>
<?php
foreach($r as $r){
echo "<option value=\"$r->collegename\">$r->collegename </option>";
}
?>
</select>
<?php }else{ ?>
<select name="mycollegename">
<option value="">Select State</option>
</select>
<?php } ?>

PHP: Echo value of selected item from a dependable dropdown menu

I am currently working with a Dependable dropdown menu that functions with the help of jQuery and PHP. The values are being pulled of MySQL database. Is there away to php echo the selected value of a dependable drop down menu?
EXAMPLE
HTML/PHP
<form action="" method="post">
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update"
disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update"
disabled="disabled">
<option value="">----</option>
</select>
</form>
Please add jquery.js.
your html code
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update" disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update" disabled="disabled">
<option value="">----</option>
</select>
//jquery code for source list
<script type="text/javascript">
$(document).ready(function(){
$('#gender').change(function() {
if ($(this).val()!='') {
$("#category").load("postfile.php",{gender_id: $(this).val()});
$("#category").removeAttr('disabled');
}
});
//code on change of sel_source
$('#category').change(function() {
if ($(this).val()!='') {
$("#colour").load("postfile.php",{category_id: $(this).val()});
$("#colour").removeAttr('disabled');
}
});
});
</script>
//postfile.php
//your mysql connection other things goes here
//code for category
$objDb = new PDO('mysql:host=localhost;dbname=dbname', 'ur_username', 'ur_password');
if(isset($_REQUEST['gender_id']) && !empty($_REQUEST['gender_id'])) {
$sql = "SELECT * FROM `categories` WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($_REQUEST['gender_id']));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if(!empty($list)) {
$output = '<option value="">Select</option>';
foreach($list as $row) {
$output .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
} else {
$output = '<option value="">Select</option>';
}
echo $output;
}
//code for color
if(isset($_REQUEST['category_id']) && !empty($_REQUEST['category_id'])) {
$sql = "SELECT * FROM `categories` WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($_REQUEST['category_id']));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if(!empty($list)) {
$output = '<option value="">Select</option>';
foreach($list as $row) {
$output .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
} else {
$output = '<option value="">Select</option>';
}
echo $output;
}
Hope this will help you.
You are going to have to write a JavaScript function that retrieves the selected value or option from the first HTML select field. This function commonly writes out a new URL path to the current page with the addition of some concatonated Get Variables:
<script type="text/javascript">
getSelectedOptionValue() {
// create some variables to store your know values such as URL path and document
var myPath = " put the URL path to the current document here ";
var currentPage = "currentPage.php";
// get the values of any necessary select fields
var carMake = document.getElementById("carMake").value;
// write out the final URL with the Get Method variables you want using concatnitation
var getMethodURL = myPath + currentPage + "?carMake='" + carMake + "'";
// function refreshes page using the function made URL
window.location.replace( getMethodURL );
}
</script>
Since the second select field is dependent on the first you have to assume that the user is going to make a selection from the first choice of options. This means that the function that retrieves the value of the primary select field must run in response to a change in the fields selection. For example
<select name="carMake" id="carMake" onchange="getSelectedOptionValue();">
Depending on how you have set up your DB, you may want either the value of the option tag or the string presented to the user between the option tags...this is up to you keeping in mind how you may re-query the information if your original record set hasn't already pulled up the necessary info to write the second set of select option tags.
To write out the second select field using php simply repeat the while loop you have used for the first. This time replace your SQL statement with a new one using a variable in which you have stored the value retrieved from the new URL using the get method
<?php
// here I am using the more generic request method although you could use the get as well
$carMake = $_REQUEST['carMake'];
sql_secondSelectField = "SELECT * FROM tbl_carModels WHERE carMake = $carMake";
// Run new query and repeat similar while loop used to write your first select field ?>

Categories