How to select value based on previous 2 input field in php - javascript

I have 3 select fields. Now based on 1st one I need to select 2nd and 3rd. but the problem is I need 2nd field value as a where condition in sql query for 3rd field. I am able to select value for 2nd and 3rd on the basis for 1st one but not able to put where condition on the basis of 2nd field.
For more clarity below is my PHP code.
<div class="form-row">
<div class="form-group col-md-4">
<label>Employee Code*</label>
<?php
$sql = "select * from issue where status like '%not%' ";
$stmt = $conn->prepare ( $sql );
$result = $stmt->execute();
// $row = $stmt->fetch ( PDO::FETCH_ASSOC );
echo '<select class="custom-select form-control"
name="employeecode"id="employeecode"onChange="getin(this.value),geti(this.value),getinfoa(this.value)" required>';
echo '<option value="">'.'</option>';
foreach($stmt as $row){
echo '<option value ="'.$row['employeecode'].'">'.$row['employeecode'].'</option>';
}
echo '</select>';
?>
</div>
<div class="form-group col-md-4 ">
<label>Employee Name*</label>
<input class="form-control" placeholder="Employee Name" name="employeename" type="text" id="employeename" required>
<div class="invalid-feedback">This field is requires</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label>Category*</label>
<select class="custom-select form-control" name="cat" id="cat" onChange="info(this.value)"required>
</select>
</div>
<div class="form-group col-md-4">
<label>Issue No.*</label>
<select class="custom-select form-control" name="issue_id" id="issue_id" onChange="getinfo(this.value)" required>
</select>
</div>
</div>
Now when I select employee code it will automatically fill the category and Issue No. But now I also want to pass category value to Issue No so that issue no come on the basis of employee code and category.
Below is the script code:
<script>
function geti(employeecode){
var employeecode = $('#employeecode').val();
//alert(employeecode);
$.ajax({
url:'populate_subcategory.php',
type:"POST",
data:"name="+employeecode+"&type=employeecode",
cache: false,
dataType: 'json',
success: function(response){
$('#cat').empty();
$('#cat').append("<option></option>")
for (var i = 0; i < response.length; i++) {
//alert(response);
$("#cat").append('<option value=' + response[i] + '>' + response[i] +'</option>');
}
}
});
}
function getinfoa(employeecode){
var employeecode = $('#employeecode').val();
//alert(employeecode);
$.ajax({
url:'subcategory.php',
type:"POST",
data:"name="+employeecode+"&type=employeecode",
cache: false,
dataType: 'json',
success: function(response){
$('#issue_id').empty();
$('#issue_id').append("<option></option>")
for (var i = 0; i < response.length; i++) {
//alert(response);
$("#issue_id").append('<option value=' + response[i] + '>' +
response[i] +'</option>');
}
}
});
}
</script>
PHP file for script:
<?php
if($type=='employeecode')// for category
{
$name=($_POST['name']);
$data = array();
$sql = "select * from issue where status like '%Not%' and employeecode = '$name' ";
$stmt = $conn->prepare ( $sql );
$result=$stmt->execute();
foreach($stmt as $row){
array_push($data, $row['cat']);
}
echo json_encode($data);
}
if($type=='employeecode')// for issue No
{
$name=($_POST['name']);
$data = array();
$sql = "select * from issue where status like '%Not%' and employeecode =
'$name'";
$stmt = $conn->prepare ( $sql );
$result=$stmt->execute();
foreach($stmt as $row){
array_push($data, $row['issue_id']);
}
echo json_encode($data);
}
?>
Now I want sql query for issue No like this :
$sql = "SELECT * FROM issue WHERE status LIKE '%Not%' AND employeecode =
'$name' AND cat='category selected'";
Please help me to understand the same.

Related

Fetch data from msql into selectpickers for editing

I have a code which inserts data from a modal form into two related tables, namely inventory_order table and inventory_order_product table. That code is working fine but my problem comes when I want to fetch the same data back into the modal form for editing. The code for fetch single is only retrieving data for the first line in the selectpicker while the remaining are not retrieved. Please if my question is not clear refer to the image below and please bear with me I'm a novice in php, ajax and mysql.
$(document).on('click', '.update', function(){
var inventory_order_id = $(this).attr("id");
var btn_action = 'fetch_single';
$.ajax({
url:"order_action.php",
method:"POST",
data:{inventory_order_id:inventory_order_id, btn_action:btn_action},
dataType:"json",
success:function(data)
{
$('#orderModal').modal('show');
$('#inventory_order_name').val(data.inventory_order_name);
$('#inventory_order_date').val(data.inventory_order_date);
$('#inventory_order_address').val(data.inventory_order_address);
$('#span_product_details').html(data.product_details);
$('#payment_status').val(data.payment_status);
$('.modal-title').html("<i class='fa fa-pencil-square-o'></i> Edit Order");
$('#inventory_order_id').val(inventory_order_id);
$('#action').val('Edit');
$('#btn_action').val('Edit');
}
})
});
if($_POST['btn_action'] == 'fetch_single')
{
$query = "
SELECT * FROM inventory_order WHERE inventory_order_id = :inventory_order_id
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':inventory_order_id' => $_POST["inventory_order_id"]
)
);
$result = $statement->fetchAll();
$output = array();
foreach($result as $row)
{
$output['inventory_order_name'] = $row['inventory_order_name'];
$output['inventory_order_date'] = $row['inventory_order_date'];
$output['inventory_order_address'] = $row['inventory_order_address'];
$output['payment_status'] = $row['payment_status'];
}
$sub_query = "
SELECT * FROM inventory_order_product
WHERE inventory_order_id = '".$_POST["inventory_order_id"]."'
";
$statement = $connect->prepare($sub_query);
$statement->execute();
$sub_result = $statement->fetchAll();
$product_details = '';
$count = '';
$count = $count++;
foreach($sub_result as $sub_row)
{
$product_details .= '
<script>
$(document).ready(function(){
$("#product_id'.$count.'").selectpicker("val", '.$sub_row["product_id"].');
$(".selectpicker").selectpicker();
});
</script>
<span id="row'.$count.'">
<div class="row">
<div class="col-md-8">
<select name="product_id[]" id="product_id'.$count.'" class="form-control selectpicker" data-live-search="true" required>
'.fill_product_list($connect).'
</select>
<input type="hidden" name="hidden_product_id[]" value="'.$sub_row["product_id"].'" />
</div>
<div class="col-md-3">
<input type="text" name="quantity[]" class="form-control" value="'.$sub_row["quantity"].'" required />
</div>
<div class="col-md-1">
';
if($count == '')
{
$product_details .= '<button type="button" name="add_more" id="add_more" class="btn btn-success btn-xs">+</button>';
}
else
{
$product_details .= '<button type="button" name="remove" id="'.$count.'" class="btn btn-danger btn-xs remove">-</button>';
}
$product_details .= '
</div>
</div>
</div><br />
</span>
';
}
$output['product_details'] = $product_details;
echo json_encode($output);
}
Problem in your code is with variable $count.As in your backend code this is declare outside your foreach.. loop so when first time your loop will run it will have correct value i.e : 0 but you never increment it that's why it is only giving correct value for first selectpicker. Instead you need to increment its value to set value for second value ,third and so on. i.e :
foreach($sub_result as $sub_row)
{
//you code html and jquery
$count = $count++;//add this inside for loop
}
Also, i don't why you have given $count = ''; . Instead , it should be $count = 0;

Pulling MYSQL (PHP) values in to JSON -> Error Undefined

I'm trying to push information from MYSQL, in a PHP File named edit_v and, in my main file "editar_v" I want to fill the input fields inside my forms so after that, user can edit the info related to the vehicle that is stored in my database. For that, I'm using Ajax, so the page doesn't get reloaded/changed.
Here is my main code of editar_v.php:
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<form method="POST" action="editar_v.php">
<div class="form-row">
<div class="form-group col-md-12">
<label for="input_veiculo_editar">Escolha o veículo que pretende editar:</label>
<select class="custom-select my-1 mr-sm-2" id="dropdown_matricula">
<option selected>Veículos Disponíveis</option>
<?php
$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
$sql = "SELECT id, matricula FROM veiculo";
$result = $conn->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
echo "<option value='".$row['id']."'>".$row['matricula']."</option>";
}
}
?>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for"input_marca">Marca do Veículo:</label>
<input type="text" class="form-control" id="input_marca" disabled value="NOTHING">
</div>
<div class="form-group col-md-6">
<label for="input_modelo">Modelo do Veículo:</label>
<input type="text" class="form-control" id="input_modelo" disabled>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for"input_cilindrada">Cilindrada (CV):</label>
<input type="text" class="form-control" id="input_cilindrada" disabled>
</div>
<div class="form-group col-md-6">
<label for="input_potencia">Potencia do Veículo:</label>
<input type="text" class="form-control" id="input_potencia" disabled>
</div>
</div>
<div class="form-group">
<label for="input_combustivel">Combustível:</label>
<input type="text" class="form-control" id="input_combustivel" disabled>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for"input_ano">Ano do Veículo:</label>
<input type="text" class="form-control" id="input_ano" disabled>
</div>
<div class="form-group col-md-6">
<label for="input_modelo">Modelo do Veículo:</label>
<input type="text" class="form-control" id="input_modelo" disabled>
</div>
</div>
<div class="form-group">
<label for="input_escolaID">Escola de Condução a que pertence:</label>
<select class="custom-select my-1 mr-sm-2" id="inlineFormCustomSelectPref" disabled>
<option selected></option>
<?php
$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
$sql = "SELECT id_escola, nome FROM escola";
$result = $conn->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
echo "<option value='".$row['id_escola']."'>".$row['nome']."</option>";
}
}
?>
</select>
</div>
<input type="button" value="Procurar Veículo" id="procuraveiculo">
<input type="button" value="Editar Veículo" id="adicionar_veiculo">
<span id="jsonresultado"></span>
</form>
</div>
</div>
</div>
Inside the same file, i have the following javascript / jquery:
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
console.log("Document ready!");
$("#procuraveiculo").on('click', function() {
var e = document.getElementById("dropdown_matricula");
var strUser = e.options[e.selectedIndex].text;
alert(strUser);
$.ajax({
method: "POST",
url: "admin_pages/veiculo_pages/edit_v.php",
data: {matriculaPHP:strUser},
complete: function(data) {
var yourDataStr = JSON.stringify(data);
var result = yourDataStr;
console.log(result[0].marca);
},
error : function (data) {
console.log("error:"+data.message);
console.log("DATA ERROR:: " + data.msg);
},
dataType: "JSON",
});
});
});
</script>
So in this part of the code, i give the user the option to select one of the available vehicles in the database.
After that, i send it to php file in matriculaPHP, and this is working properly.
Now, there is my edit_v.php:
<?php
$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
$matricula = $_POST['matriculaPHP'];
$sql = "SELECT marca, modelo, cilindrada, potencia, combustivel, ano, mes, escola_id_escola FROM veiculo WHERE matricula='$matricula'";
$result = $conn->query($sql);
if($conn->query($sql) == TRUE)
{
echo "Base de dados conectada!";
}
else
{
echo "Error " . $sql . "<br>" . $conn->error;
}
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
print json_encode($data);
header('Content-type: application/json');
echo json_encode($data);
?>
Conclusion: When i execute my code, i get the right values from the database. Example: [{"marca":"Citroen","modelo":"C3","cilindrada":"1100","potencia":"60","combustivel":"Gasolina","ano":"2002","mes":"6","escola_id_escola":"1"}]
But when i try to read the code inside the JSON/Javascript, it gives me the error of UNDEFINED.
I would like to get some of your help so i can solve this problem and keep working in my project.
First of all, your edit_v.php file is not outputting valid JSON due to the line that prints the connection status of the database.
If you want to do that then you'll have to output all the data as part of an array.
For example:
header('Content-type: application/json');
$res = array(
'success' => false,
'errors' => array(),
'data' => null
);
$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo")
$matricula = $_POST['matriculaPHP'];
$sql = "SELECT marca, modelo, cilindrada, potencia, combustivel, ano, mes, escola_id_escola FROM veiculo WHERE matricula='$matricula'";
$result = $conn->query($sql);
if($conn->query($sql) == TRUE)
{
// echo "Base de dados conectada!";
$res['success'] = true;
$res['data'] = array();
while ($row = $result->fetch_assoc())
{
$res['data'][] = $row;
}
}
else
{
$res['errors'][] = "Error " . $sql . "<br>" . $conn->error;
}
echo json_encode($data);
Also, the Content-Type header has to be set before any output is made.
In the complete function of your JQuery request, you are converting the JSON data to a String using JSON.stringify(...) which should not be. You should try changing the complete function to success and use the data as is.
...
success: function(data) {
console.log(data[0].marca);
},
...
Problem is with JavaScript and PHP JSON.
When there is only one element in array, there is no record zero.
Please use code: console.log(data.marca) instead of console.log(data[0].marca) and you will see result.
You have to check if in JSON is just one element array or few and then use proper code.
Solved
finally I solved my problem with the help of this big community!
Editar_v.php jquery:
$("#procuraveiculo").on('click', function() {
var e = document.getElementById("dropdown_matricula");
var strUser = e.options[e.selectedIndex].text;
alert(strUser);
$.ajax({
method: "POST",
url: "admin_pages/veiculo_pages/edit_v.php",
data: {matriculaPHP:strUser},
success: function(data) {
var marca = data[0].marca;
var modelo = data[0].modelo;
var cilindrada = data[0].cilindrada;
var potencia = data[0].potencia;
var combustivel = data[0].combustivel;
var ano = data[0].ano;
var mes = data[0].mes;
var idEscola = data[0].escola_id_escola;
And now, the PHP file: edit_v.php:
<?php
header('Content-type: application/json');
$res=array(
'success' => false,
'errors' => array(),
'data' => null
);
$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
$matricula = $_POST['matriculaPHP'];
$sql = "SELECT marca, modelo, cilindrada, potencia, combustivel, ano, mes, escola_id_escola FROM veiculo WHERE matricula='$matricula'";
$result = $conn->query($sql);
if($conn->query($sql) == TRUE)
{
// echo "Base de Dados conectada!";
$res['success'] = true;
$res['data'] = array();
while($row = $result->fetch_assoc())
{
$res['data'][] = $row;
}
}
else
{
$res['errors'][] = "Error " . $sql . "<br>" . $conn->error;
}
echo json_encode($res['data']);
?>
This is working very well, and now I do understand how jquery works in this situations. Also understood what was my fault in PHP.
My thanks to #Omari Celestine and #Norbul and to stackoverflow community.

JavaScript error and database update

I have a problem with my database and doing the update of it. I have a database table stock with 5 columns (stock_id, p_id, brand_id, cat_id, availability). I want to do an update from the frontend. So when the popup show up and I fill in the form, UPDATE doesn't work. I have 3 files. First one stock.php that read database and works fine. the seconf one that open if you click edit looks like this:
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST['rowid']) {
$id = $_POST['rowid']; //escape string
$query = "SELECT * FROM stock WHERE stock_id = $id";
$results = $database->get_results( $query );
foreach( $results as $row ){
$cat_id = $row['cat_id'];
$brand_id = $row['brand_id'];
$p_id = $row['p_id'];
?>
<form method="post" name="form">
<input id="stock_id" name="stock_id" type="hidden" value="<?php echo $row['stock_id'];?>"/>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">CATEGORY</label>
<select id="category" name="category" class="form-control">
<?php
$qex = "SELECT * FROM category";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['cat_id']; ?>"<?php
if ($cat_id == $rowex['cat_id'])
echo 'selected'; ?>><?php echo $rowex['cat_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">BRAND</label>
<select id="brand" name="brand" class="switchable form-control">
<?php
$qex = "SELECT * FROM brand";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['brand_id']; ?>"<?php
if ($brand_id == $rowex['brand_id'])
echo 'selected'; ?> class="brand_<?php echo $rowex['cat_id'];?>"><?php echo $rowex['brand_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">PRODUCT NAME</label>
<select id="product" name="product" class="switchable form-control">
<?php
$qex = "SELECT * FROM product";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['product_id']; ?>"<?php
if ($product_id == $rowex['product_id'])
echo 'selected'; ?> class="product_<?php echo $rowex['brand_id'];?>"><?php echo $rowex['product_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">IN STOCK</label>
<input type="number" id="availability" name="availability" value="<?php echo $row['availability'];?>" class="form-control"/>
</div>
</div>
<div class="clearfix"></div>
<div>
<input type="submit" value="Update Data" class="pull-right btn btn-primary submit" style="margin-right:15px;"/>
<span class="pull-left error" style="display:none;margin-left:15px;"> Please Enter Valid Data</span>
<span class="pull-left success" style="display:none;margin-left:15px;"> Data updated!</span>
<div class="clearfix"></div>
</div>
</form>
<?php
}
?>
<script type="text/javascript" >
$(document).ready(function(){
$(function() {
$(".submit").click(function() {
var stock_id = $("#stock_id").val();
var category = $('select[name="category"]').val()
var brand = $('select[name="brand"]').val()
var product = $('select[name="product"]').val()
var availability = $("#availability").val();
var dataString =
'stock_id='+ stock_id +
'&brand=' + brand +
'&category=' + category +
'&product=' + product +
'&availability=' + availability
;
if(
stock_id=='' ||
brand=='' ||
category=='' ||
product=='' ||
availability==''
){
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "update-stock.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
$("#category").change(function () {
if ($(this).data('options') == undefined) {
$(this).data('options', $('select.switchable option').clone());
}
var id = $(this).val();
var that = this;
$("select.switchable").each(function () {
var thisname = $(this).attr('name');
var theseoptions = $(that).data('options').filter('.' + thisname + '_' + id);
$(this).html(theseoptions);
});
});
//then fire it off once to display the correct elements
$('#category').trigger('change');
});/** Document Ready Functions END **/
</script>
<?php } ?>
This is my code for update-stock.php that supposed to be updating the database:
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST) {
$stock_id = $_POST['stock_id'];
$brand = $_POST['brand'];
$category = $_POST['category'];
$product = $_POST['product'];
$availability = $_POST['availability'];
$update = array(
'p_id' => $product,
'brand_id' => $brand,
'cat_id' => $cat,
'availability' => $availability
);
$where_clause = array(
'stock_id' => $stock_id
);
$updated = $database->update( 'stock', $update, $where_clause, 1 );
}
?>
I have a 2 problems.
Update doesn't work at all. I am just getting the message Please Enter Valid Data
My form doesn't show up the correct value of the PRODUCT NAME. Example: In the database and my main table that read information from database product name is 2.1.1 but when I click on edit and open my pop-up form that show up 2.1.3 for example.
Thank you so much in advance for your help.
This one works PERFECT fetch_brand.php:
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST['rowid']) {
$id = $_POST['rowid']; //escape string
$query = "SELECT * FROM brand WHERE brand_id = $id";
$results = $database->get_results( $query );
foreach( $results as $row ){
$cat_id = $row['cat_id'];
?>
<form method="post" name="form">
<input id="brand_id" name="brand_id" type="hidden" value="<?php echo $row['brand_id'];?>"/>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">CATEGORY</label>
<select id="category" name="category" class="form-control">
<?php
$qex = "SELECT * FROM category";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['cat_id']; ?>"<?php
if ($cat_id == $rowex['cat_id'])
echo 'selected'; ?>><?php echo $rowex['cat_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">BRAND NAME</label>
<input type="text" id="brand_name" name="brand_name" value="<?php echo $row['brand_name'];?>" class="form-control"/>
</div>
</div>
<div class="clearfix"></div>
<div>
<input type="submit" value="Update Data" class="pull-right btn btn-primary submit" style="margin-right:15px;"/>
<span class="pull-left error" style="display:none;margin-left:15px;"> Please Enter Valid Data</span>
<span class="pull-left success" style="display:none;margin-left:15px;"> Data updated!</span>
<div class="clearfix"></div>
</div>
</form>
<?php
}
?>
<script type="text/javascript" >
$(document).ready(function(){
$(function() {
$(".submit").click(function() {
var brand_id = $("#brand_id").val();
var brand_name = $("#brand_name").val();
var category = $('select[name="category"]').val()
var dataString =
'brand_id='+ brand_id +
'&brand_name=' + brand_name +
'&category=' + category
;
if(
brand_id=='' ||
brand_name=='' ||
category==''
){
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "update-brand.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
});/** Document Ready Functions END **/
</script>
<?php } ?>
update-product.php :
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST) {
$p_id = $_POST['p_id'];
$brand = $_POST['brand'];
$category = $_POST['category'];
$product = $_POST['product'];
$update = array(
'product_name' => $product,
'brand_id' => $brand,
'cat_id' => $cat
);
$where_clause = array(
'p_id' => $p_id
);
$updated = $database->update( 'product', $update, $where_clause, 1 );
}
?>
This one works excellent! So I am pretty sure that I made a mistake in my code for the stock.

unable to fetch data in multiple dropdown

I am unable to fetch the data in the second dropdown(which is depended upon the first dropdown). e.g. when we select country then the relevant state should be displayed but it doesn't. see my code.
my html
<?php
require 'dbconfig.php';
?>
<label class="control-label">Select Distict</label>
<div class="form-group">
<div class="col-lg-6">
<select class="form-control" name=dist id=dist>
<option value='' selected>Select</option>
<?Php
$ddObj = new USER($DB_con);
$table= "tbl_dist";
$sel = $ddObj->dropdowndist($table);
foreach ($sel as $val) {
echo "<option value=$val[dist_id]>$val[dist_name]</option>";
}
?>
</select>
</div>
</div>
<label class="control-label">Select Block</label>
<div class="form-group">
<div class="col-lg-6">
<select class="form-control" name=block id=block>
</select>
</div>
</div>
my jquery
<script>
$(document).ready(function() {
$('#dist').change(function(){
var dist_id=$('#dist').val();
$('#block').empty(); //remove all existing options
$.get('ddblock.php',{'dist_id':dist_id},function(return_data){
$.each(return_data.data, function(key,value){
$("#block").append("<option value='" + value.block_id +"'>"+value.block_name+"</option>");
});
}, "json");
});
});
</script>
ddblock.php
<?Php
$dist_id=$_GET['dist_id'];
if(!intval($dist_id)){
echo "Data Error";
exit;
}
require 'class.user.php';
$ddObj = new USER($DB_con);
$table = "tbl_block";
$result = $ddObj->fetch_block($table,$dist_id);
$main = array('data'=>$result);
echo json_encode($main);
}
?>
class.user.php
public function fetch_block($table,$dist_id){
try
{
$sel = $this->db->prepare("SELECT * FROM $table WHERE block_dist_id=:dist_id");
$sel->bindValue(':dist_id', $dist_id);
$sel->execute();
$rs = $sel->setFetchMode( PDO::FETCH_ASSOC );
return $sel;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}

populating a 2nd select box based off the 1st one using ajax and PHP

I'm going a little nuts here. I know this has been answered a few times before but I can't seem to get it. I must be missing something very obvious.
I need the options of the second select input to be dynamically populated from a DB based on selection of the 1st select input. I have tested the getShowByBand.php code and it produces the intended results. My guess is the problem lies in the javascript file. Please take a look at my code and see if you can help.
testForm.php
<form role="form">
<div class="well" id="generalIDRows">
<div class="row">
<div class="col-md-6 padding-top-10">
<div class="form-group">
<label for="band">Choose Band:</label>
<select id="band" name="band" class="form-control">
<option value="">Band Name</option>
<?php
$sql = "SELECT bandID,bandName FROM Band";
$bandq = mysqli_query($link, $sql);
while($row = mysqli_fetch_array($bandq))
{
$band_ID=$row["bandID"];
$band=$row["bandName"];
echo '<option value="' . $band_ID . '">' . $band .'</option>';
}
?>
</select>
<script src="js/getShowByBand.js" type="text/javascript"></script>
</div>
</div>
<div class="col-md-6 padding-top-10">
<div class="form-group">
<label for="show">Choose Show:</label>
<select id="show" name="show" class="form-control">
<option value="">--Select Show--</option>
</select>
</div>
</div>
</div>
</div>
</form>
getShowByBand.js
$(document).ready(function()
{
$(".band").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "womhScripts/getShowByBand.php",
data: dataString,
cache: false,
success: function(html)
{
$(".show").html(html);
}
});
});
});
getShowByBand.php
<?php
$link=mysqli_connect("localhost","womhproduction","Derkadeepd0ng","womh");
if (mysqli_connect_errno())
echo "failed to connect" . mysqli_connect_error();
if($_POST)
{
$id=$_POST['id'];
$showSQL = mysqli_query($link,"SELECT showID FROM Act WHERE bandID =" . $id . ";");
$showResults = mysqli_num_rows($showSQL);
if($showResults > 0)
{
echo "<option selected disabled>--Select show--</option>";
while($showRow = mysqli_fetch_array($showSQL))
{
$showID= $showRow['showID'];
$showNameSQL = mysqli_query($link, "SELECT showName FROM Shows WHERE showID=". $showID . ";");
$showNameResults = mysqli_num_rows($showNameSQL);
if($showNameResults > 0)
{
while($showNameRow = mysqli_fetch_array($showNameSQL))
{
$showName = $showNameRow['showName'];
echo '<option value= "' . $showID . '">' . $showName . '</option>';
}
}
}
}
}
?>
Use $("#band").change... dot is used to select class.
try to change this $(".band") to this $("#band") on your javascript you are calling on change for the class you should do it by id.

Categories

Resources