I have form like this.
<form action="Barang.php" method="POST" class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-md-3"
for="id_suplier">ID suplier :</label>
<div class="col-md-5">
<select class="selectpicker" title="Ketikkan ID suplier" data-width="100%" data-live-search ="true" id="id_suplier" autocomplete="off" onchange="" required>
<?php
$query = $db->query('SELECT * FROM tb_suplier');
?>
<?php
while($row = $query->fetch(PDO::FETCH_ASSOC)){ ?>
<option value="<?php echo $row['id_suplier']; ?>"><?php echo $row['id_suplier']; ?></option>
<?php
}
?>
</select>
</div>
<span class="badge badge-info" style="margin-top:10px;" id="namasup">nama suplier</span>
</div>
</form>
<script type="text/javascript">
$('#id_suplier').on('change', function() {
var id_suplier=$("#id_suplier").val();
$.ajax({
type:"POST",
url:"Barang.php",
dataType:'json',
success:function(data) {
$("#namasup").html(data.namasup);
}
});
})
</script>
And I want send the request to Barang.php, and I want to process in getSuplier(), and get name suplier to database and put the value on id=namasup. how can I process it?
And here code Barang.php
<?php
class Barang
{
function getSuplier($id){
$query = $this->db->query("SELECT nama from tb_suplier where id='$id' ");
$result=$query->fetch(PDO::FETCH_ASSOC);
return $result;
}
}
Maybe you can do this
class Barang
{
function getSuplier($id){
// your code here ....
}
}
$barang = new Barang;
$barang->getSupplier($_GET['id']);
In addition to that, Jeff is right. You are not sending your id_suplier to the server. Please send it.
I think you no need to request name from database every time you change data in selection
In my opinion you can use this code
in html
<html>
<body>
<form action="Barang.php" method="POST" class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-md-3"
for="id_suplier">ID suplier :</label>
<div class="col-md-5">
<select class="selectpicker" title="Ketikkan ID suplier" data-width="100%" data-live-search ="true" id="id_suplier" autocomplete="off" onchange="" required>
</select>
</div>
<span class="badge badge-info" style="margin-top:10px;" id="namasup">nama suplier</span>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function createOption(datas)
{
var html = "";
for (var i in datas){
var data = datas[i];
html = html + '<option value="'+data['id']+'">'+ data['name'] +'</option>';
}
return html;
}
$(document).ready(function() {
//get all data
$.ajax({
type:"POST",
url:"Barang.php",
type: "json",
//dataType:'json',
success:function(res) {
var datas = JSON.parse(res);
$("#id_suplier").html(createOption(datas));
//tigger change event
$('#id_suplier').change();
}
});
$('#id_suplier').on('change', function(){
//change name in span
var name = $('#id_suplier').find(":selected").text();
$("#namasup").html(name);
});
});
</script>
</body>
in php
class Barang
{
//Method for get all datas
public function getSupliers(){
//I don't have you database so I skip this part
// $query = $this->db->query("SELECT nama from tb_suplier");
// $result=$query->fetch(PDO::FETCH_ASSOC);
// return $result;
//mock data
$datas = [[
'id' => 1,
'name' => 'Test 1',
],[
'id' => 2,
'name' => 'Test 2',
],[
'id' => 3,
'name' => 'Test 3',
]];
return $datas;
}
}
$class = new Barang();
$datas = $class->getSupliers();
echo json_encode($datas);
Hope this help
Related
I made this work already but somehow it stopped working. I want to display informations from database related to the chosen data from the select box without clicking a button so I used ajax.
The button "Approve Clearance" is used for another action which is I wished to used after the display of data.
There is a div with id #records which is hidden and will show upon display of data.
<div class="card-body">
<form id="gform" action="action/actionclearance.php" method="POST">
<label>Student ID</label>
<select id="stud_id" name="stud_id" class="form-control col-md-6" required>
<option selected="selected">Select Student ID</option>
<?php
$mysqli = new mysqli ('localhost', 'u220931635_arug', 'Smarvcdsl2019', 'u220931635_arug') or die (mysqli_error($mysqli));
$resultset = mysqli_query($mysqli, "SELECT * FROM tbl_student where delete_flag = 0");
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<option><?php echo $rows["stud_id"]; ?></option>
<?php } ?>
</select>
<br>
<button type="submit" class="btn btn-primary btn-md" name="gclear" id="gclear" class="gclear"><i class="fas fa-check-double"></i> Approve Clearance</button>
</form>
</div>
<div class="card-footer">
<div id="display">
<div class="row" id="heading" style="display:none;">
<tr>
<th class="text-center">
<div class="col-sm-6">
<strong>Student</strong>
</div>
</th>
</tr>
</div>
<div class="row" id="records">
<tr>
<td>
<div class="col-sm-6">
<span id="stud_fname"></span>
<span id="stud_mname"></span>
<span id="stud_lname"></span>
<span id="stud_suffix"></span>
</div>
</td>
</tr>
</div>
<div class="row" id="no_records">
<div class="col-lg-12 text-center">
Plese select Student ID to view details</div>
</div>
</div>
</div>
</div>
Below is the ajax code I used to display data without clicking a button.
<script>
$(document).ready(function(){
// code to get all records from table via select box
$("#stud_id").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'stud_id='+ id;
$.ajax({
url: 'getstudent.php',
dataType: "json",
data: dataString,
cache: false,
success: function(studentData) {
if(studentData) {
$("#heading").show();
$("#no_records").hide();
$("#stud_fname").text(studentData.stud_fname);
$("#stud_mname").text(studentData.stud_mname);
$("#stud_lname").text(studentData.stud_lname);
$("#stud_suffix").text(studentData.stud_suffix);
$("#records").show();
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
});
});
});
</script>
This is the getstudent.php which is connected to the database where ajax gets datas to display.
<?php
include("../configAdmin.php");
if($_REQUEST['stud_id']) {
$mysqli = new mysqli ('localhost', 'u220931635_arug', 'Smarvcdsl2019', 'u220931635_arug') or die (mysqli_error($mysqli));
$resultset = mysqli_query($mysqli, "SELECT * FROM tbl_student where delete_flag = 0 AND stud_id ='".$_REQUEST['stud_id']."'");
while( $rows = mysqli_fetch_assoc($resultset) ) {
$data = $rows;
}
echo json_encode($data);
} else {
echo 0;
}
?>
without using ajax you can do this
<select id="stud_id" name="stud_id" class="form-control col-md-6" required>
<option selected="selected">Select Student ID</option>
<?php
$mysqli = new mysqli ('localhost', 'u220931635_arug', 'Smarvcdsl2019', 'u220931635_arug') or die (mysqli_error($mysqli));
$resultset = mysqli_query($mysqli, "SELECT * FROM tbl_student where delete_flag = 0");
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<option value="<?php echo $rows["stud_id"]; ?>"><?php echo $rows["stud_id"]; ?></option>
<?php } ?>
</select>
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.
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.
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();
}
}
I have a select drop down on my form, of my categories from my database
Question: When I select a category from my select form, if it has a parent id
how am I able to attract that parent id to the hidden input value on my form.
Controller
<?php
class Pages extends Admin_Controller {
public function index() {
$this->load->model('admin/catalog/model_catalog_pages');
$data['page_categories'] = array();
$results = $this->model_catalog_pages->get_category();
foreach ($results as $result) {
if ($result['parent_id']) {
// If Child Category
$data['page_categories'][] = array(
'category_id' => $result['category_id'],
'parent_id' => $result['parent_id'],
'name' => $this->model_catalog_pages->get_parent_name($result['parent_id']) .' > '. $result['name']
);
} else {
// If Parent Category
$data['page_categories'][] = array(
'category_id' => $result['category_id'],
'parent_id' => $result['parent_id'],
'name' => $result['name']
);
}
}
$this->load->view('template/catalog/page_form_view', $data);
}
}
?>
View
<form action="" method="post" enctype="multipart/form-data" id="form-page" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label" >Categories</label>
<div class="col-sm-10">
<select class="form-control" name="category_select" id="category_select">
<?php foreach ($page_categories as $category) {?>
<option value="<?php echo $category['category_id'];?>"><?php echo $category['name'];?></option>
<?php }?>
</select>
<input type="hidden" id="category_parent_id" name="category_parent_id" value="" />
</div>
</div>
</form>
The way I would tackle this problem is to add a data attribute to the dropdown menu options and then use some javascript to detect if its present. Try this:
<select class="form-control" name="category_select" id="category_select">
<?php foreach ($page_categories as $category) {?>
<option value="<?php echo $category['category_id'];?>" <?php echo isset($category['parent_id']?'data-parent_id="'.$category['parent_id]'"':'';?>><?php echo $category['name'];?></option>
<?php }?>
</select>
<input type="hidden" id="category_parent_id" name="category_parent_id" value="" />
The Javascript:
var dd = document.getElementById('category_select');
var hidden = document.getElementById('category_parent_id');
dd.addEventListener('change',selectParent,false);
function selectParent(){
for(var i in dd.options){
if(dd.options[i].selected == true){
if(dd.options[i].dataset.parentid){
hidden.value = dd.options[i].dataset.parentid
}else{
hidden.value = "";
}
}
}
}
selectParent();
Here is a fiddle of the javscript doing its thing, I've used type='text' input field in the fiddle to demonstrate that it works but this the code will still work with type='hidden'
http://jsfiddle.net/cpr63ajb/1/
Edit: I've tweaked the javascript so that when the page loads, it should select whatever is in the dropdown menu by default. This avoids the need of adding a dummy 'please select' option. (old JS code available here: http://jsfiddle.net/cpr63ajb).
Thanks to #Ben Broadley working now.
By his way on the option i added data-parentid and echoed parend id so looks like this now
data-parentid="<?php echo $category['parent_id'];?>
And added his script all working
<?php
class Pages extends Admin_Controller {
public function index() {
$this->load->model('admin/catalog/model_catalog_pages');
$data['page_categories'] = array();
$results = $this->model_catalog_pages->get_category();
foreach ($results as $result) {
if ($result['parent_id']) {
// If Child Category
$data['page_categories'][] = array(
'category_id' => $result['category_id'],
'parent_id' => $result['parent_id'],
'name' => $this->model_catalog_pages->get_parent_name($result['parent_id']) .' > '. $result['name']
);
} else {
// If Parent Category
$data['page_categories'][] = array(
'category_id' => $result['category_id'],
'parent_id' => $result['parent_id'],
'name' => $result['name']
);
}
}
$this->load->view('template/catalog/page_form_view', $data);
}
}
?>
View
<form action="" method="post" enctype="multipart/form-data" id="form-page" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label" >Categories</label>
<div class="col-sm-10">
<select class="form-control" name="category_select" id="category_select">
<?php foreach ($page_categories as $category) {?>
<option value="<?php echo $category['category_id'];?>" data-parentid="<?php echo $category['parent_id'];?>"><?php echo $category['name'];?></option>
<?php }?>
</select>
<input type="hidden" id="category_parent_id" name="category_parent_id" value="" />
</div>
</div>
</form>
<script type="text/javascript">
var dd = document.getElementById('category_select');
var hidden = document.getElementById('category_parent_id');
dd.addEventListener('change',function(e){
for(var i in dd.options){
if(dd.options[i].selected == true){
if(dd.options[i].dataset.parentid){
hidden.value = dd.options[i].dataset.parentid
}else{
hidden.value = "";
}
}
}
},0);
</script>