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.
Related
I'm new in PHP.
I have a database with 5 columns. "id" "fldName" "fldPrice" "fldSupplier" and "fldPackage".
I have a HTML table with select options where I output "fldName" where "fldPackage" has a spesific value. I have made this work, but I would also like to output the corresponding "fldPrice" from the selected "fldName" when it's chosen. I'm stuck on how to do this.
This is my php:
<?php
function conTroller(){
include("includes/dbh.php");?>
<?php $sql = "SELECT * FROM tbl_price WHERE fldPackage='controller'";
$result = mysqli_query($conn, $sql);
if($result->num_rows> 0){
$options= mysqli_fetch_all($result, MYSQLI_ASSOC);}
foreach ($options as $option) { ?>
<option><?php echo $option['fldName']; ?> </option><?php }}
?>
and this is my HTML
<td><b>Electrical package</b></td>
<td>
<select id="1" class="custom-select" required onchange="ePkg(event)">
<option selected value="">None</option>
<?php conTroller(); ?>
</select>
</td>
<td>I want "fldPrice" to update here when I choose from the options</td>
<td>istL</td>
<td>Select controller</td>
Can anyone help?
I have been reading, googling and looking for similar problems. The biggest problem for me is that I'm not really sure what to search for.
For the simplicity for only updating price when selectbox changed, I suggest to use DOM Manipulation using Javascript
<?php
function conTroller() {
include("includes/dbh.php");
$sql = "SELECT * FROM tbl_price WHERE fldPackage='controller'";
$result = mysqli_query($conn, $sql);
if($result->num_rows> 0){
$options= mysqli_fetch_all($result, MYSQLI_ASSOC);}
foreach ($options as $option) { ?>
<!-- add attribute "data-price" so javascript can get price value from the selected option -->
<option data-price="<?php echo $option['fldPrice']; ?>"><?php echo $option['fldName']; ?> </option><?php
}
}?>
<td><b>Electrical package</b></td>
<td>
<!-- add a function in onchange to update price whenever selectbox changed -->
<select id="1" class="custom-select" required onchange="ePkg(event); updatePrice(this)">
<option selected value="">None</option>
<?php conTroller(); ?>
</select>
</td>
<!-- add attibute "id" so we can access the element to be updated -->
<td id="price-field">I want "fldPrice" to update here when I choose from the options</td>
<td>istL</td>
<td>Select controller</td>
<script>
// function to update price from selected option
function updatePrice(selectbox) {
var price = selectbox.selectedOptions[0].attributes['data-price'].value || '- no price set -';
document.getElementById('price-field').innerHTML = price;
}
</script>
For more advanced flow (eg: getting more product info other than price like description, etc), you will need a separate php file for displaying product info and fetch it using AJAX call. See some tutorial about AJAX and PHP
Steps I did:
PDO is safer.
The first function returns data.
The other is making a presentation.
An additional div with id='fldPrice' will be the place to display the price.
A significant part of the code was done by javascript
function getPackage() {
$db = conn();
$sql = "SELECT id, fldName, fldPrice, fldSupplier, fldPackage FROM tbl_price WHERE fldPackage='controller'";
$sth = $db->prepare($sql);
$sth->execute();
return $sth->fetchAll(PDO::FETCH_ASSOC);
}
function conTroller() {
$options = getPackage();
foreach ($options as $option) {
echo "<option>" . $option['fldName'] . "</option>";
}
}
function ePkg(ev) {
let prices = JSON.parse('<?php echo json_encode(getPackage()); ?>');
let select = document.getElementById('1');
let fldName = select.options[select.selectedIndex].value;
for (let i = 0; i < prices.length; i++) {
if (prices[i]['fldName'] === fldName) {
let d = document.getElementById('fldPrice');
d.innerHTML = 'Prices: ' + prices[i]['fldPrice'];
}
}
}
<td><b>Electrical package</b></td>
<td>
<select id="1" class="custom-select" required onchange="ePkg(event)">
<option selected value="">None</option>
<?php conTroller(); ?>
</select>
</td>
<td>I want "fldPrice" to update here when I choose from the options</td>
<td>List</td>
<td>Select controller</td>
<div id="fldPrice"></div>
Hello everyone I need help with my php code
I need to use a dependency list , I have three select fields (filiere,Semestre,module)
the first list is filiere select which takes all the the filieres we have in the data base and we can select one of them
the secend list is semestre which has 6 options (S1,S2,S3,S4,S5,S6)
the last one is module which depends on the both previous ones (filiere & semestre )
we have in the database this tables
filiere ( Nom_filiere )
module ( Num_module,Nom_module,Nom_filiere,Nom_semestre)
I succeeded to make the last list depends on the first (filiere) but I still have a problem to add a condition on the second one (semestre)
this is my code :
// select.php
$query = "SELECT * FROM filiere";
$result1 = mysqli_query($dbc, $query);
<script type="text/javascript">
function getID(val){
$.ajax({
type: "post",
url: "get_module.php",
data:"get_filiere=" + val,
success: function(data){
$("#NOM_MODULE").html(data);
}
});
}
</script>
<label for="Nom_filiere" id="Nom_filiere" >Filieres</label>
<select onChange="getID(this.value);" id="Nom_filiere" name="Nom_filiere">
<?php while($row1 = mysqli_fetch_array($result1)):;?>
<option value="<?php echo $row1[0];?>"><?php echo $row1[0];?></option>
<?php endwhile;?>
</select>
<label for="NOM_semestre">Semestre</label>
<select id="NOM_semestre" name="NOM_semestre" >
<option value="S1"> S1</option>
<option value="S1"> S2</option>
<option value="S1"> S3</option>
<option value="S1"> S4</option>
<option value="S1"> S5</option>
<option value="S1"> S6</option>
</select>
<label for="NOM_MODULE"> Module</label>
<select class="mdb-select md-form" id="NOM_MODULE" name="NOM_MODULE[]" multiple>
<option selected="" disabled="">selest module</option>
</select>
// get_module.php :
if(isset($_POST['get_filiere'])) {
$fid = $_POST['get_filiere'];
$query2 = "SELECT * from module where NOM_Filiere ='$fid'";
if($result2 = mysqli_query($dbc, $query2)) {
while($row = mysqli_fetch_array($result2)){
echo "<option value=".$row['NUM_Module'].">".$row['Nom_module']."</option>";
}
} else {
echo "Something went wrong while executing query :: $query";
}
exit;
}
this code works fine with the first condition I just need to add a condition on Semestre
There are at least two libraries I know that could help you achieve this ...
Form-Field-Dependency: http://emranahmed.github.io/Form-Field-Dependency/
DependsOn: https://dstreet.github.io/dependsOn/
They will help you control the dependencies between fields by configuring in a declarative way.
Hey im trying to create a dynamic dropdown list using PHP and AJAX. Its worth mentioning that im using visual composer on my wordpress site. So i have to make it a shortcode for visual composer.
Here is currently what ive got.
function dropdownmenu() {
include_once "connection.php";
?>
<div class="make">
<label>Make</label>
<select name="makelist" onchange="getId(this.value);">
<option value="">Select Make</option>
<?php
$query = "select distinct(Make) from websitemasterlist order by Make ASC";
$results = mysqli_query($conn, $query);
foreach($results as $info) {
?>
<option value="<?php echo $info[Make]; ?>"><?php echo $info[Make]; ?></option>
<?php
}
?>
</select>
</div>
<div class="model">
<label>Model</label>
<select name="model" id="modellist">
<option value="">Select Model</option>
</select>
</div>
<script src="code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
function getId(val){
$.ajax({
type: "POST",
url: "getdata.php",
data: "make="+val,
success: function(data){
$("#modellist").html(data);
}
});
}
</script>
<?php
}
add_shortcode('dropdownform','dropdownmenu');
?>
I think the error is somewhere in the ajax. because my ajax is weak.
here is the code for the secondary dynamic dropdown
<?php
include_once "connection.php";
if (!empty($_POST["make"])) {
$make = $_POST["make"];
echo $make;
$query = "SELECT distinct(Model) FROM websitemasterlist where Make=$make";
$results = mysqli_query($conn, $query);
foreach ($results as info2){
?>
<option value="<?php echo info2["Model"]; ?>"><?php echo info2["Model"]; ?></option>
<?php
}
}
?>
The first dropdown works. but the second dropdown doesn't show any choices when i make a choice on the first dropdown. Any help would be appreciated thank you. Its also worth mentioning that when i try to echo the make .... i dont see the make. so im pretty sure the ajax portion is messed up.
The errors I'm getting from the console
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>'
;
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 ?>