I am trying to get the value from a drop down menu (list) and use that value to create another drop down menu. I have a database in mysql, in that database is a list of departments and then each department has a list of courses. What I am trying to do is have a drop down list for the departments which I have already created and then use the value the user selected to make a drop down list for the courses.
EDIT: Updated code:
JavaScript dropmysql.js
<!-- start: Container -->
<div class="container">
<!-- start: Contact Form -->
<div class="title">
<h4>Contact Form</h4>
</div>
<!-- start: Contact Form -->
<div id="contact-form">
<form method="post" action="assets/upload.php" enctype="multipart/form-data">
<fieldset>
<div class="clearfix">
<label for="name"><span>Name:</span>
</label>
<div class="input">
<input tabindex="1" size="18" id="name" name="name" type="text" value="">
</div>
</div>
<div class="clearfix">
<label for="email"><span>Email:</span>
</label>
<div class="input">
<input tabindex="2" size="25" id="email" name="email" type="text" value="" class="input-xlarge">
</div>
</div>
<div class="dropdown">
<label for="department"><span>Department:</span>
</label>
<select tabindex="3" type="text" name="Department">
<?php while($dept=m ysqli_fetch_array($result)) { echo "<option value=\" ".$dept['dname']."\ ">".$dept[ 'dname']. "</option>"; } //<option value="volvo">Volvo</option>
?>
</select>
</div>
<div class="dropdown" id="course-container">
<!-- SELECT WILL BE PLACED USING JAVASCRIPT -->
</div>
<div class="actions">
<p>
<label for="file"><span>Select file to upload:</span>
</label>
<input tabindex="8" type="file" name="fileToUpload" id="fileToUpload">
</p>
<p>
<input tabindex="3" type="submit" value="Upload File" name="submit" class="btn btn-succes btn-large">
</p>
</div>
</fieldset>
</form>
</div>
<!-- end: Contact Form -->
</div>
<!-- end: Container -->
<!-- start: Java Script -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="js/jquery-1.8.2.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/flexslider.js"></script>
<script src="js/carousel.js"></script>
<script src="js/dropmysql.js"></script>
<script def src="js/custom.js"></script>
<!-- end: Java Script -->
PHP upload.php
<?php
include ("../config/database.php");
if (isset($_POST) && !empty($_POST)) {
$department = $_POST['department'];
$query = "SELECT * FROM courses WHERE dname = '{$department}'";
while (mysql_fetch_assoc($query)) {
echo '<option value="{$value}>{$name}</option>"'; // Loop through the database again and echo them here
}
}
?>
PHP ddown.php:
<?php
include ("../config/database.php");
if (isset($_POST) && !empty($_POST)) {
$department = $_POST['department'];
$query = "SELECT * FROM courses WHERE dname = '{$department}'";
while (mysql_fetch_assoc($query)) {
echo '<option value="{$value}>{$name}</option>"'; // Loop through the database again and echo them here
}
}
?>
First it will be helpful to add an id/class to the first select such as:
<select tabindex="3" type="text" name="Department" id="department">
<option value="BSEN">BSEN</option>
<option value="CPSC">CPSC</option>
<option value="ENGG">ENGG</option>
</select>
You'll need to setup the 2nd dropdown list with empty options, or setup an empty div similar to this
<div id="course-container">
<!-- SELECT WILL BE PLACED USING JAVASCRIPT -->
</div>
Then a javascript file similar to this could be used:
$(function() {
var course_container = $("div#course-container");
var data = {};
$('select#department').change(function() {
$(course_container).html("<select id=\"courses\"></select>");
var courses = $("select#courses");
var d = document.getElementById("department");
data['department'] = d.options[d.selectedIndex].value;
$.ajax({
url: "path/to/php/script.php",
type: "post",
data: data,
success: function(response) {
$(courses).innerHTML = response;
}
});
});
});
Then just a php script like this:
<?php
if (isset($_POST) && !empty($_POST)) {
$department = $_POST['department'];
$query = "SELECT * FROM `DATABASE` WHERE `DEPARTMENT` = {$department}";
while (mysql_fetch_assoc($query)) {
echo '<option value="{$value}>{$name}</option>"'; // Loop through the database again and echo them here
}
}
If you have a select element that looks like this:
<!-- language: lang-html -->
<input type="hidden" id="depthidden" name="depthidden">
<select tabindex="3" id="Department">
<option value="BSEN">BSEN</option>
<option value="CPSC">CPSC</option>
<option value="ENGG">ENGG</option>
</select>
Run this code:
<!-- language: lang-js -->
var d = document.getElementById("Department");
document.getElementsById('depthidden').Value = d.options[d.selectedIndex].value;
The above is just a JS demo to help you.
The php section:
$dname = mysql_real_escape_string($_POST['depthidden']);
while($dept= mysqli_fetch_assoc($result))
{
if($dname==$dept[dname])
echo "<option value = '".$dept[dname]."' selected>".$dept[dname]."</option>";
else
echo "<option value = '".$dept[dname]."'>".$dept[dname]."</option>";
}
The $dname is the dept name to be populated. Otherwise, remove the if and keep the else part.
Related
i'm trying to auto populate text-box when drop-down is selected. I've tried some code but nothing happen i already included the jquery file in my code.
I have a database table called services and the column are service_id, service_name, service_price.
Here's My view
<div class="form-group-inner">
<div class="row">
<div class="col-lg-1">
<label class="login2 pull-right pull-right-pro">Service</label>
</div>
<div class="col-lg-4">
<div class="form-select-list">
<select class="form-control custom-select-value" id="service_name" name="service_name">
<option>Select Service</option>
<?php foreach ($service as $services): ?>
<option value="<?php echo $services->service_id; ?>"><?php echo $services->service_name; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
</div>
<div class="form-group-inner">
<div class="row">
<div class="col-lg-1">
<label class="login2 pull-right pull-right-pro">Price</label>
</div>
<div class="col-lg-4">
<input type="text" id="price" name="price" class="form-control" />
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#service_name').on('change', function() {
var service_id=$("service_name").val();
$.post("<?php echo base_url();?>/records/getprice/" + service_id,
function(data){
$('#price').val(data.service_price);
});
}
<script>
Controller
function add_form($patient_id){
$data['service']=$this->services_model->get_all_services();
$data['value'] = $this->patient_model->get_selected_patient($patient_id);
$this->load->view('header/header');
$this->load->view('Records/add_records',$data);
$this->load->view('footer/footer');
}
function getprice($service_id){
$laiza=$this->db->get_where("services",array("service_id"=>$service_id));
foreach ($laiza->result() as $row){
$arr = array('service_price' => $row->service_price);
header('Content-Type: application/json');
echo json_encode($arr);
}
}
I expect that when i select a data from dropdown the textbox will populate the price base on the selected item dropdown
ID selector # missing when your getting the Service_Name value
Change the same to
var service_id=$("#service_name").val();
or
var service_id= this.value;
<script>
$(document).ready(function () {
$('#service_name').on('change', function() {
var service_id=$("#service_name").val();
$.post("<?php echo base_url();?>/records/getprice/" + service_id,
function(data){
$('#price').val(data.service_price);
});
}
<script>
I know php is a server-side language and html a client-side language and to do this i would use javascript but i don't know how to do.
Can someone help me to write the script called changeFunction()?
This is my form in index.php:
<form method="POST">
<div class="row"style="margin-top: 5%;">
<div class="col-3">
</div>
<div class="col-6">
<label for="inputUsername">Insert username</label>
<input type="text" class="form-control" name="inputUser" style="margin-bottom: 2%">
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="inputGroupSelect01">Convert account type to: </label>
</div>
<select class="custom-select" id="inputGroupSelect01" name="inputSelected">
<option selected>Choose...</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
<button type="button" class="btn btn-outline-primary" onclick="changeFunction()">Submit</button>
</div>
</div>
<div class="col-3">
</div>
</div>
</form>
This is my query in query.php:
<?php
$var1= $_POST["inputGroupSelect01"];
$var2= $_POST["inputUser"];
require 'connection.php';
$sql = "UPDATE user SET typeAcc =".$var1." WHERE username=".$var2;
?>
I hope this is the solution you want .
First add the following div in you html form <div id='resultDiv' ></div>
so your html form code be like this
<form method="POST" >
<div class="row"style="margin-top: 5%;">
<div class="col-3">
<h2>Testing Form</h2>
</div>
<div class="col-6">
<label for="inputUsername">Insert username</label>
<input type="text" class="form-control" name="inputUser" style="margin-bottom: 2%" id="inputUser">
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="inputGroupSelect01">Convert account type to: </label>
</div>
<select class="custom-select" id="inputGroupSelect01" name="inputSelected">
<option selected>Choose...</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
<button type="button" class="btn btn-outline-primary" onclick="changeFunction()">Submit</button>
</div>
<!-- this need to be added -->
<div id='resultDiv' ></div>
</div>
<div class="col-3">
</div>
</div>
</form>
Second add the jQuery and following script to your code
two jquery variable define userName and role which is later passed as data
and if server response is SUCCESS then success condition executed or you can send data or particular error message by setting ERROR with YOUR ERROR TEXT
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script type='text/javascript'>
function changeFunction(){
var userName = $('#inputUser').val();
var role =$('#inputGroupSelect01').val();
$.ajax({
method: "POST",
url: "server.php",
data: JSON.stringify( { "userId": userName, "userRole": role } ),
dataType: "text",
success: function (response){
if(response=='SUCCESS'){
$('#resultDiv').append('<br/>Successful Updated'+response);
}else{
$('#resultDiv').append('<br/>Error'+ response);
}
}
});
}
</script>
**Third ** you have to write the new server.php file with following code
<?php
$var1= $_POST["userId"]; // change here userId as used in jquery block
$var2= $_POST["userRole"];// change here userRole as used in jquery Block
//require 'connection.php';
$sql = "UPDATE user SET typeAcc =".$var1." WHERE username=".$var2;
//suppose query is executed successfull then
//it will return no of rows updated
$query_result = mysql_query($query);
//SUCCESS_CONDITION is normally if number of row updated is 1 in return
///of query execution so kindly define by your own way
$num_rows = mysql_num_rows($query_result);
//if($num_rows==1 || define your own SUCCESS_CONDITION){
if($num_rows ==1){
$result ='SUCCESS';
}else{
$result ='ERROR';
}
echo $result;
?>
I hope it will help
Thanks
Ask for help if needed
You can do this using PHP but you need to check $_POST data.
if(isset($_POST['inputGroupSelect01']) && isset($_POST['inputUser;]){
$var1= $_POST["inputGroupSelect01"];
$var2= $_POST["inputUser"];
require 'connection.php';
$sql = "UPDATE user SET typeAcc =".$var1." WHERE username=".$var2;
}
By the way, that code is entirely vulnerable. You are taking 2 inputs from users and placing them directly, and placing them into a SQL query.
What if my input for var2 was '; DROP TABLE user; ?
Recently i have asked same question but this is improved one.
i have some select options on my webpage and as someone selects option i want to get data from database for the same. i tried to do but i am geting data for only one select . what if i want to get data with combination of 3 select fields . how can i achieve this. please help !!!
here is my html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Filter</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" >
<link rel="stylesheet" href="css/style.css">
<link href="https://fonts.googleapis.com/css?family=Exo+2" rel="stylesheet">
</head>
<body>
<div id="rooms"></div>
<div class="container main-section" id="main">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="location">Location:</label>
<select name="location" id="location" class="form-control">
<option value="">Select</option>
<option value="candolim">Candolim</option>
<option value="calangute">Calangute</option>
<option value="baga">Baga</option>
<option value="anjuna">Anjuna</option>
<option value="morjim">Morjim</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="stay_type">Property Type:</label>
<select name="stay_type" id="stay_type" class="form-control">
<option value="">Select</option>
<option value="hotel">Hotel</option>
<option value="villa">Villa</option>
<option value="studio">Studio</option>
<option value="resort">Resort</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="room_type">Room Type:</label>
<select name="room_type" id="room_type" class="form-control">
<option value="">Select</option>
<option value="standard">Standard</option>
<option value="deluxe">Deluxe</option>
<option value="suit">Suit</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group"><br>
<input type="submit" name="submit" value="Search" class="btn btn-success">
</div>
</div>
</div>
</div>
<div class="display">
</div>
<script src="js/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="js/script.js" type="text/javascript"></script>
</body>
</html>
and this is my script --
$(document).ready(function(){
getAllRooms();
function getAllRooms(){
$.ajax({
url:'action.php',
method: 'POST',
data:{rooms:1},
success:function(response){
$('.display').html(response);
}
});
}
$('#location').change(function(){
var location = $(this).val();
$.ajax({
url:'action.php',
method: 'POST',
data:{location:location},
success:function(response){
$('.display').html(response);
}
});
});
});
and finally here is my action.php
<?php
$conn=mysqli_connect('localhost','cms_user','12345','rooms');
if (isset($_POST['rooms']) || isset($_POST['location'])){
if (isset($_POST['rooms'])){
$query_all = "SELECT * FROM rooms ORDER BY rand() ";
}
if(isset($_POST['location'])){
$location = $_POST['location'];
$query_all = "SELECT * FROM rooms WHERE location = '$location' ORDER BY rand() ";
}
$query_run = mysqli_query($conn,$query_all);
if (mysqli_num_rows($query_run)>0){
while ($row = mysqli_fetch_array($query_run)){
$room_id = $row['id'];
$room_name = $row['name'];
$location = $row['location'];
$stay_type = $row['stay_type'];
$room_type = ucfirst($row['room_type']);
$image = $row['image'];
$price = $row['price'];
echo "
<div class='container rooms'>
<div class='row'>
<div class='col-md-4'>
<img src='img/$image' alt='room' width='100%'>
</div>
<div class='col-md-6'>
<h2>$room_name</h2>
<p>$stay_type</p>
<h4 class='text-success'>$location</h4>
</div>
<div class='col-md-2'>
<br><br><br><br>
<h4 class='text-primary'>$room_type</h4>
<h4>Rs : $price </h4>
<a href='#'><input type='submit' name='book' value='Book Now' class='btn btn-success'></a>
</div>
</div></div>
";
}
} else {
echo "<center><h3>No Properties available</h3></center>";
}
}
?>
Thanks !
In your jquery, you should have a .change function for all 3 select boxes - when any of the select boxes change, grab and send all 3 values to your php page.
$(document).ready(function(){
getRooms();
function getRooms(){
var location = $('#location').val();
var stay_type = $('#stay_type').val();
var room_type = $('#room_type').val();
$.ajax({
url: 'action.php',
method: 'POST',
data: {
"location" : location,
"stay_type" : stay_type,
"room_type" : room_type,
},
success:function(response){
$('.display').html(response);
}
});
}
$('#location').change(function(){
getRooms();
}
$('#room_type').change(function(){
getRooms();
}
$('#stay_type').change(function(){
getRooms();
}
});
In your php page, get the value of all 3 possible post variables and start building your query based on those values. It helps to split up the sql statement into parts and then just combine them at the very end.
# setting parameters from the post
$room_type = isset($_POST['room_type']) ? $_POST['room_type'] : '';
$location = isset($_POST['location']) ? $_POST['location'] : '';
$stay_type = isset($_POST['stay_type']) ? $_POST['stay_type'] : '';
# defaults
$select = "SELECT * FROM rooms";
$where = " WHERE 1 = 1"; # to have a default where that is always true
$order_by = " ORDER BY rand()"; # you can always change the order by this way
if ($room_type != '') {
$where .= " AND room_type = '$room_type'";
}
if ($location != '') {
$where .= " AND location = '$location'";
}
if ($stay_type != '') {
$where .= " AND stay_type = '$stay_type'";
}
$sql = $select . $where . $order_by;
/* execute query using the $sql string and output results here */
This will also not require you to set a rooms value since it will still execute a query for all items.
If you want PHP to treat $_GET/$_POST['select2'] as an array of options just add square brackets to the name of the select element like this:
Then you can access the array in your PHP script
<?php
header("Content-Type: text/plain");
foreach ($_GET['select2'] as $selectedOption)
echo $selectedOption."\n";
$_GET may be substituted by $_POST depending on the
I have a drop down list, and user can select multi options.
So this is part of my code in firtfile.inc
<div class="col-md-8">
<!-- Change report heading so we can grab it on the report page -->
<select name="SearchIn[]" multiple="multiple" onchange="javascript:this.form.Heading.value=this.options[this.selectedIndex].text;" required="required" title="Section">
<option value="" disabled selected>Select</option>
<?php
//Loop over the options
for($i=0;$i<sizeof($SearchCriteria);$i++){
?>
<option value="<?php echo $SearchCriteria[$i]['value'];?>"<?php if($SearchCriteria[$i]['value']=='FacultyName'){echo ' selected="selected"';}?>>
<?php echo $SearchCriteria[$i]['display'];?>
</option>
<?php
}//!End of looping over search criteria
?>
</select>
<!-- Hidden heading field for search report -->
<input type="hidden" name="Heading" valtue="" />
</div>
in another php file, I have included firstfile.inc, and i want to get the list of options that user has selected from drop down list.
so I have the folloing in the php file to get the selected options.
$Heading = $dat->if_default('Heading', '');
but it only gives me the first option that the user has selected, but I need all of them. How can I get them?
First of all, I highly recommend that you use jQuery, it will make any DOM manipulation a lot easier.
It's not clear what output you expect, but supposing you're expecting a comma separated string like:
Criteria1, Criteria2, Criteria3
You could:
1) Just use PHP to give you that, with something like:
$SearchIn = $_POST["SearchIn"];
$selectedArr = array();
foreach($SearchCriteria as $item) {
if (in_array($item["value"], $SearchIn)) {
$selectedArr[] = $item["display"];
}
}
$criteria = implode(", ", $selectedArr); // will contain: Criteria1, Criteria2, Criteria3
2) If you want to do it on the client and store the values in <input id="heading"/>, you can use jQuery and do this (your HTML would change a little, to include the IDs):
<form action="index.php" method="POST">
<div class="col-md-8">
<!-- Change report heading so we can grab it on the report page -->
<select id="section" name="SearchIn[]" multiple="multiple" required="required" title="Section">
<option value="" disabled selected>Select</option>
<?php for($i = 0; $i < sizeof($SearchCriteria); $i++) { ?>
<option value="<?php echo $SearchCriteria[$i]['value'];?>"<?php if($SearchCriteria[$i]['value']=='FacultyName'){echo ' selected="selected"';}?>>
<?php echo $SearchCriteria[$i]['display'];?>
</option>
<?php } ?>
</select>
<!-- Hidden heading field for search report -->
<input id="heading" type="hidden" name="Heading" value="" />
</div>
<input type="submit">
</form>
<script>
$('#section').on("change", function() {
selectedArray = new Array();
$(this).find("option:selected:not([disabled])").each(function() {
selectedArray.push(this.text);
});
$("#heading").val(selectedArray.join(", "));
});
</script>
3) For a pure JavaScript solution (use the same HTML as above):
<script>
document.getElementById("section").onchange=function(){
selectedArray = new Array();
for (x = 0; x < this.length; x++) {
if (this[x].selected && !this[x].disabled) {
selectedArray.push(this[x].text);
}
}
document.getElementById("heading").value = selectedArray.join(", ");
};
</script>
I try to update text box value according to 2 dropdown. 1 drop down contain price1 and other drop down contain price 2, now I want that when user select price from both drop down then textbox display like that "price1 + price2 = total" How can I marge both value in single textbox value ? my price comes from database. Here is FIDDLE
PHP CODE
<div class="three columns">
<div class="picker">
<select name="city" required>
<option value="" disabled>Select</option>
<?php
$result = mysqli_query($con,"SELECT * FROM area");
while($row = mysqli_fetch_array($result))
{
?>
<option value="New"><?php echo $row['city']."( $ ".$row['area'].")";; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="four columns">
<div class="picker">
<select name="position" required>
<?php
$result = mysqli_query($con,"SELECT * FROM pricing");
while($row = mysqli_fetch_array($result))
{
?>
<option value="<?php echo $row['position']; ?>"><?php echo $row['position']."( $ ".$row['price'].")"; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row">
<div class="two columns">
Total
</div>
<div class="ten columns">
<div class="field">
<input class="input" type="total" id="total" placeholder="" name="total" disabled/>
</div>
</div>
</div>
add a class on both combo and write one event this way:
$('.combo').change(function() {
$('#firstvalue').val(parseInt($('#combo').val()) +parseInt($('#combo1').val()));
});
FIDDLE DEMO
or you can do this way:
$('.combo').change(function() {
$('#firstvalue').val($('#combo').val() +"+"+$('#combo1').val()+"=");
$('#firstvalue1').val(parseInt($('#combo').val()) +parseInt($('#combo1').val()));
});
SECOND DEMO
use this..
$(document).ready(function() {
$('.combo').change(function() {
$('#firstvalue').val(parseInt($('#combo').val()) +parseInt($('#combo1').val()));
});
$('#combo1').change(function() {
$('#firstvalue1').val($('#combo1').val());
});
});
you can do it by using variables:
if you wanted to sum of two dropdown options then you have to give integer value of the seond dropdown not the string(like a3,a4 should be 3,4). see demo html.
$(document).ready(function() {
price1=0;
price2 =0;
$('#combo').change(function() {
price1= this.value;
$('#firstvalue').val(parseInt(price1)+parseInt(price2));
});
$('#combo1').change(function() {
price2 = this.value;
$('#firstvalue').val(parseInt(price1)+parseInt(price2));
});
});
demo