I have two dropdown lists as a part of a form I'm creating, both of which have options that are being pulled from a mysql database. I would like the options in the second dropdown to change based on the selection in the first dropdown. I know how to do this using Javascript when the second list is static, but I would like both dropdowns to dynamically pull from the database. Below is the HTML and Javascript I'm currently using. Any ideas would be great.
HTML:
<form>
<label for="org_name">Organization Name:</label>
<select id="org_name" name="org_name" onchange="configureDropDownLists(this,'submitter_name')">
<option value="empty"> </option>
<?php
mysql_connect("database", "username", "password") or die(mysql_error ());
mysql_select_db("databaseName") or die(mysql_error());
$query = "SELECT * FROM Table";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo "<option value='" . $row['org_name'] . "'>" . $row['org_name'] . "</option>";
}
mysql_close();
?>
</select>
<label for="submitter_name">Request Submitted By:</label>
<select id="submitter_name" name="submitter_name">
<option value="empty"> </option>
</select>
<input type="Submit" value="Submit">
</form>
Javascript:
function configureDropDownLists(org_name,submitter_name) {
var org = new Array('Submitter 1', 'Submitter 2');
switch (org_name.value) {
case 'org':
document.getElementById(submitter_name).options.length = 1;
for (i = 0; i < org.length; i++) {
createOption(document.getElementById(submitter_name), org[i], org[i]);
}
break;
default:
document.getElementById(submitter_name).options.length = 1;
break;
}
createOption(document.getElementById(submitter_name), 'Other', 'Other');
if (org_name.value === 'empty') {
document.getElementById(submitter_name).options.length = 1;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
As suggested, AJAX was the answer. For anyone curious who comes across this, below is the solution I came up with. I left the HTML unchanged other than removing onchange="configureDropDownLists(this,'submitter_name')" from the first dropdown. Instead of the above Javascript, I used the below AJAX and PHP. Works really nicely.
JQuery:
$(document).ready(function() {
$("#org_name").on("change", function() {
var orgName = document.getElementById("org_name").value;
$.post('admin_list.php', { org: orgName }, function(result) {
$('#submitter_name').html(result);
}
);
});
});
and the referenced PHP page:
<?php
mysql_connect("database", "username", "password") or die(mysql_error ());
mysql_select_db("databaseName") or die(mysql_error());
$org_name = $_REQUEST['org'];
$query = mysql_query("SELECT * FROM Table WHERE user = '$org_name'");
while($row = mysql_fetch_array($query)){
echo "<option>" . $row['admin_first_name'] . " " . $row['admin_last_name'] . "</option>";
}
mysql_close();
?>
Sounds like you need some AJAX to pull your data from the database, format on the server side (JSON will likely be easiest to work with), then use a callback function in Javascript to populate the second drop down based on the JSON data received.
Related
I have a button that is setup from database content as well as a select option that is setup from the same database. I would like to be able to click the button or choose from the dropdown to chose the option.
I have tried a lot of different options that I have found online. Currently I am able to alert the text I want to select but have been unable to change the dropdown.
PHP file
$q = "SELECT CONCAT(user_first, ' ', user_last) AS name1, user_id as id from users ";
$r = #mysqli_query($conn, $q);
// Count the number of returned rows:
$num = mysqli_num_rows($r);
if ($num > 0) { // If it ran OK, display the records.
echo '<select class="select" name="name1" id="Seltherapist" autofocus tabindex="1">';
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo '<option value="'.$row['id'].'">' . $row['name1'] . '</option>
';}
echo '</select>';
mysqli_free_result ($r);
} else {
echo '<p class="error">There are currently no registered users.</p>';
}
$num = mysqli_num_rows($r);
if ($num > 0) {
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo '<button name="name22" value="'.$row['name'].'" id="'.$row['id'].'" class="btn">' . $row['name'] . '</button>
';}
JavaScript File
$('button[name="name22"]').click(function(){
alert($(this).attr("value"));
alert($(this).attr("id"));
event.preventDefault();
return false;
});
I've not sure where you're getting the text from so lets just call that yourText.
let yourText = "someTextToMatch";
//By option text something like this.
$('#Seltherapist').find('option').each(function(i, v){
if ($(v).text() === yourText)
{
$(v).prop('selected', 'selected');
return false;
}
});
//by option value
$('#Seltherapist').val(yourText);
I'm trying to dynamically generate radio buttons with data in front of them. The data that is to be displayed in front of the radio button is based on a drop down selection, which also displays some data in a text box using javascript.
I tried taking the selected option in a string and use it in the next query, but I know I am doing it wrong.
Database Connection
$db = pg_connect("");
$query = "select account_name,account_code,address1,address2,address3 FROM
customers";
$result = pg_query($db,$query);
//NEW QUERY
$sql1= "select name from conferences";
$result1= pg_query($db, $sql1);
//END
//New Code
<select class="form-control" id="conference" name="conference">
<option value="">Select Conference...</option>
<?php while($rows1 = pg_fetch_assoc($result1)) { ?>
<option value="<?= $rows1['code']; ?>"><?= $rows1['name']; ?></option>
<?php } ?>
</select>
<br>
// END OF NEW CODE
Dropdown to select the data.
<select onchange="ChooseContact(this)" class="form-control"
id="account_name" name="account_name" >
<?php
while($rows= pg_fetch_assoc($result)){
echo '<option value=" '.$rows['address1'].' '.$rows['address2'].'
'.$rows['address3'].''.$rows['account_code'].'">'.$rows['account_name'].'
'.$_POST[$rows['account_code']].'
</option>';
}?>
</select>
Displaying data in the text area based on the selcted value using javascript. (The code works fine till here)
<textarea readonly class="form-control" style="background-color: #F5F5F5;"
id="comment" rows="5" style="width:700px;"value=""placeholder="Address...">
</textarea>
<script>
function ChooseContact(data) {
document.getElementById ("comment").value = data.value;
}
</script>
Displaying data in front of the radio buttons based on the selected option(This code works if I use some random value in the query, but not if I use the selected value 'account_code' from the previous query. I'm using POST GET method to carry the selected value)
<?php
//NEW CODE
$sql = "select order_number, order_date from orders where
customer_account_code = '3000614' and conference_code='DS19-'"; <-Data
gets displayed when put random value like this.
$code = $_GET[$rows['account_code']];
$conf = $_GET[$rows1['conference_code']];
$sql = "select order_number, order_date from orders where
customer_account_code = '$code' and conference_code= '$conf']"; <- But I
want to display the data against the selected value, i.e, the 'account_code'
in the variable $code from the dropdown select
//END
$res = pg_query($db,$sql);
while($value = pg_fetch_assoc($res) ){
echo "<input type='radio' name='answer'
value='".$value['order_number']." ".$value['order_date']."'>"
.$value['order_number'].$value['order_date']." </input><br />";
}
?>
I need to help to find a way to put the selected 'account_code' in a variable and use it in the $sql query.
Please try with this code : (It's work for me)
1- Add this line to your HTML <head>:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
2- Edit your CODE to this:
Dropdown to select the data:
<select class="form-control" id="account_name" name="account_name">
<option value=""></option>
<?php while($rows = pg_fetch_assoc($result)) { ?>
<option value="<?= $rows['address1'].' '.$rows['address2'].' '.$rows['address3'].'-'.$rows['account_code']; ?>"><?= $rows['account_name']; ?></option>
<? } ?>
</select>
Displaying data in the text area based on the selected value using jQuery:
<textarea readonly class="form-control" style="background-color: #F5F5F5;"
id="comment" rows="5" style="width:700px;" value="" placeholder="Address..."></textarea>
jQuery Code:
<script type="text/javascript">
$('#comment').val($('#account_name').val()); // MAKE A DEFAULT VALUE
(function($) {
$('#account_name').change(function() {
$('#results').html(''); // REMOVE THE OLD RESULTS
var option = $(this).val();
$('#comment').val(option);
// EDIT RADIO WITH AJAX
$.ajax({
type: "POST",
url: "path/test.php",
dataType:'JSON',
data: $('#account_name').serialize()
}).done(function(data) {
for (var i = 0; i < data.length; i++) {
// ADD RADIO TO DIV RESULTS
$('#results').append('<input type="radio" name="answer" value="'+data[i].order_number+'">'+data[i].order_date+'</input><br>');
}
});
});
})(jQuery);
</script>
after that, add this HTML to your page, to show RESULTS FROM AJAX DATA
<!-- RADIOs -->
<div id="results"></div>
3- Create a new file like path/test.php
in this file, use this CODE to return values with JSON :)
<?php
header('Content-type: application/json');
// CONNECT (JUST USE YOUR CUSTOM CONNECTION METHOD & REQUIRE CONFIG FILE IF YOU WANT)
$db = pg_connect("");
$value = explode('-', $_POST['account_name']);
// EXPLODE AND GET LAST NUMBER AFTER < - >
$code = (int) end($value);
$sql = "select order_number, order_date from orders where customer_account_code = '$code'";
$res = pg_query($db, $sql);
// CREATE JSON RESULTS
$is = '';
while($data = pg_fetch_assoc($res)) {
$is .= json_encode($data).', ';
}
// AND GET ALL
echo '['.substr($is, 0, -2).']';
?>
I am attempting to submit a form immediately after a selection is made from a drop-down menu. After the form is submitted I want to send a query to a MySQL database based on the selection from the drop-down and display the retrieved text.
Currently, with what I have below, nothing is displayed, no errors are thrown. The JS submit event handler works but after the page reloads the new text is not displayed.
Any help is greatly appreciated.
The JS for submitting the form:
$(".platformSelectDropDown").change(function() {
$('.platformSelectForm').submit();
});
PHP to run after the form is submitted:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$platform = $_POST['platformSelectDropDown'];
$description = call_data($tableName, $platform)['Description'];
$application = call_data($tableName, $platform)['Application'];
}
PHP Function for querying and returning the data:
function call_data($tableName, $col, $platformName) {
include('connection.php');
$sql = 'SELECT * FROM $tableName WHERE platform_name = $platformName';
try {
return $db->query($sql);
}
catch (Exception $e) {
echo "Error! " . $e->getMessage() . "<br/>";
return array();
}
}
The Form:
<form class="platformSelectForm" method="post" action="index.php">
<select name="platformSelectDropDown" class="platformSelectDropDown">
...
</select>
<ul class="indent">
<li><?php echo($description); ?></li>
<li><?php echo($application); ?></li>
</ul>
</form>
I believe the code below will do what you want, with some improvements in security and functionality. However, please note that it's not clear to me from your code where $tableName is being set, so I just hard-coded that to be my test table. I intermingled the php and html, because it made it easier for me to work through the problem and I think it will make it easier for you to follow my solution. There's no reason why you can split it back out and functionize the php portions, similar to your original approach, if you prefer. Check it out:
<html>
<body>
<form class="platformSelectForm" id="platformSelectForm" method="post">
<?php
// Get which dropdown option is selected, if any, so can keep selected on page reload
if(!isset($_POST['platformSelectDropDown'])) {
// Not postback, default to first option ("Select One")
$p0Select = ' selected';
$p1Select = '';
$p2Select = '';
} else {
// Is postback
// Set variables for query below
$tableName = 'tbl_platforms_1';
$platformName = $_POST['platformSelectDropDown'];
// set dropdown selection to whatever was select at form submission
if($platformName == 'Platform_1') {
$p1Select = ' selected';
} elseif ($platformName == 'Platform_2') {
$p2Select = ' selected';
} else {
$p0select = ' selected';
}
}
?>
<select name="platformSelectDropDown" class="platformSelectDropDown" onchange="document.getElementById('platformSelectForm').submit()">
<option value="Select_One"<?php echo $p0Select; ?>>Select One</option>
<option value="Platform_1"<?php echo $p1Select; ?>>Platform 1</option>
<option value="Platform_2"<?php echo $p2Select; ?>>Platform 2</option>
</select>
<?php
// If dropdown value is set and does not equal "Select_One"
if(isset($_POST['platformSelectDropDown'])&& $_POST['platformSelectDropDown'] != 'Select_One') {
?>
<ul class="indent">
<?php
try {
// Set database parameters
// Replace these values with appropriate values for your database
// (okay to use an include like you did originally)
$dbhost = 'your_database_host';
$dbname = 'your_database_name';
$dbuser = 'your_database_user';
$dbpass = 'your_database_user_password';
// Create PDO
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare SQL statement and bind parameters
$stmt = $conn->prepare("SELECT * FROM $tableName WHERE platform_name = :platformName");
$stmt->bindValue(':platformName', $platformName, PDO::PARAM_STR);
// Execute statement and return results in an associative array (e.g., field_name -> value)
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Close Connection
$conn = null;
// For each row that was returned, output results
for ($i = 0; $i < count($results); $i++) {
echo '<li>' .$results[$i]['Description'] .'</li>';
echo '<li>' .$results[$i]['Application'] .'</li>';
}
} catch (Exception $e) {
echo '<li>Error! ' .$e->getMessage() . '</li>';
}
?>
</ul>
<?php
};
?>
</form>
</body>
</html>
Code I used to setup test:
DROP TABLE IF EXISTS tbl_platforms_1;
CREATE TABLE IF NOT EXISTS tbl_platforms_1 (
id int AUTO_INCREMENT NOT NULL,
platform_name varchar(20),
Description varchar(20),
Application varchar(20),
PRIMARY KEY (id)
);
INSERT INTO
tbl_platforms_1
(platform_name, Description, Application)
VALUES
('Platform_1', 'Description 1', 'Application 1'),
('Platform_2', 'Description 2', 'Application 2');
If this solves your problem, please remember to mark as answered, so everyone will know you no longer need help (and so I'll get rewarded for the hour I spent coming up with this solution :-). If this doesn't solve your problem, please provide as much detail as possible as to how the current results differ from your desired results and I will try to revise it to fit your needs. Thanks!
I have the idea of what i wanted but need assistance on how to get it done.Below is the scenerio: I have a two dropdwon. The First dropdown is fetched from the DB, which works fine. At the change event of the first dropdown,the system should go to the Database, and fetch the result into the next dropdown. see what I have done so far for assistance:
JQUERY SECTION
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#locate").change(function(){
var selectedloc = $("#locate option:selected").val();
$.ajax({type: "POST",url:"process-loc.php",data:{loca:selectedloc}}).done(function(data){
var ans=jQuery.parse(data);
//using php-mysql before
var ps = ans.res;
$("#subloc").html(ps);
});
});
});
</script>
FrontEnd(HTML)
<tr>
<th>Primary Location:</th>
<?php
$result = mysqli_query($connection,"SELECT * FROM tab_location");?>
<td>
<select name="locate" class="form-control" id="locate">
<option>Select Main Location</option>
<?php while($rw = mysqli_fetch_array($result)){ ?>
<option value="<?php echo $rw['location_name'];?>"><?php echo $rw['location_name'];?></option>
<?php };?>
</select>
</td>
</tr>
<tr>
<th>Sub Location:</th>
<td id="subloc"></td>
</tr>
Process-loc.php
if(isset($_POST["loca"])){
include 'includes/session.php';
include 'includes/db_connection.php';
include 'includes/functions.php';
$main = $_POST["loca"];
$gets = "SELECT * FROM tab_fltlocation WHERE mainloc='".$main."'";
$get = mysqli_query($connection,$gets);
$gt = mysqli_fetch_array($get);
//$nos= $gt['opsNo'];
if(mysqli_num_rows($get)>=0)
{
echo json_encode(array("res"=>$gt));//or do a dropdown using <select name='subloc'><option value=$gt['loc']>$gt['loc']</option></select>
}else{
echo json_encode(array("res"=>"0"));
}
}
?>
This is what I wants to be displayed on the Front End page for the use:
$gt['loc']
How can I achieve this.
$query = "
SELECT
tariff_name
FROM tariff_setting";
$result = mysqli_query($this->_connection, $query);
while ($row = mysqli_fetch_assoc($result))
$response[] = $row['tariff_name'];
}
$tarrifList = json_encode($response);
// $tarrifList is the response and sent it in json encode format and decode on ajax success
// Javascript Process
var obj = JSON.parse(resdata);
var areaOption = "<option value=''>Select State</option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#patientSelectState").html(areaOption);
You can change your AJAX processor to do this:
Process-loc.php
/* Above code the same */
if(mysqli_num_rows($get)>=0) {
$out = '<select id="selSubLoc"><option value="">Choose One:</option>';
foreach($gt AS $loc){
$seld = ($_POST['loca'] == $loc) ' selected' ? : '' ;
$out .= '<option value="' .$loc. '" ' .$seld. '>' .$loc. '</option>';
}
$out .= '</select>';
}else{
$out = 0;
}
echo $out;
And change your front-end code's AJAX routine to be like this:
$.ajax({
type: "POST",
url:"process-loc.php",
data:{loca:selectedloc}
}).done(function(recd){
$("#subloc").html(recd);
});
The data received back from PHP will be in HTML format unless you use dataType: to change it, so you can build the HTML over on the PHP side and then just plop it into the #subloc table cell.
On the event of the first box call the function containing the ajax which would retrieve information from the database. This ajax call will get data according to the first input.
Now query your database and echo the results in a foreach loop(you can make a tag there only).
In the ajax 'success:' catch the data and display it.
//from the database
foreach ($info as $product)
{
echo "<option value=".$product['childsticker_id'].">".$product['name']</option>";
}
//ajax call page
success: function(result)
{
$("#states").html(result);
}
http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html
I have searched a lot on the internet for a possible solution to my issue, but there is nothing that can help me. I am not an expert on PHP/MySQL.
My Issue:
I have two dropdown select box. On the basis of first dropdown option, second dropdown options will be populated. This is working.
Now I need to get all the values of the second dropdown by selecting one option (like "Select All"), or by clicking on a button and post (which I have used as I don't know how to use the Select All option).
Upon POST, it should create separate tables for each value. And the table name would be something like "table_valuename".
And also what will be the query to select data from a different table using those values and store them to their respective databases. Databases which are getting created on the above step.
Here is my code:
<?php
$db = new mysqli('localhost','root','redhat','echodeve_mfb_temp');//set your database handler
$query = "SELECT bp_id,bp_name FROM mfb_billing";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$categories[] = array("bp_id" => $row['bp_id'], "val" => $row['bp_name']);
}
$query = "SELECT bp_id, hospital_name FROM mfb_hospital";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$subcats[$row['bp_id']][] = array("bp_id" => $row['bp_id'], "val" => $row['hospital_name']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
?>
<html>
<head>
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 1; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].bp_id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
// subcatSelect.options.length = 0; //delete all options if any present
for(var i = 1; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].hospit);
}
}
function selectAll()
{
selectBox = document.getElementById("subcatsSelect");
for (var i = 0; i < selectBox.options.length; i++)
{
selectBox.options[i].selected = true;
}
}
</script>
</head>
<body onload='loadCategories()'>
<form id="reportvalue" action="file2.php" method="post">
<select id='categoriesSelect'>
<option value="1">Select Billing Provider</option>
</select>
<select name="hospitalname" id="subcatsSelect" multiple="multiple">
<option value="all">Select Hospital</option>
</select>
<?php
//$a = $_REQUEST['hospitalname'];
//echo $a;
//foreach ($_GET['hospitalname'] as $selectedOption)
// echo $selectedOption."\n";
?>
<input type="submit" value="generate" onclick="selectAll();">
</form>
</body>
</html>