unable to fetch data in multiple dropdown - javascript

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();
}
}

Related

Why a request to the database is reflected through the form, but not sent through AJAX

JQuery connected, AJAX probably works correctly, because when I change select in the console the values are correct. But the query to the database doesn't change. Checking var_dump($_POST['filter']) shows that there value from previous request.
If I wrap select in a form and send it via POST using submit button, the requests are sent.
Where can there be an error here?
And how to add a condition, so that when selecting "All" the query will just be to all items "SELECT * FROM orders, without the condition "WHERE?
<script>
$('#filter').change(function() {
$.ajax({
method: "POST",
url: "thispage.php",
data: {
filter: $("#filter").val()
},
success: function(response) {
console.log($("#filter").val())
}
});
});
</script>
<?php
require_once __DIR__ . "/database/database.php";
$item1 = $_POST['item1'];
$worker_name = $_POST['worker_name'];
$worker_company = $_POST['worker_company'];
$errors = [];
if (empty($item1)) {
$errors['item1'] = true;
}
if (empty($errors)) {
$sql = "INSERT INTO `orders`(`order_dish1`, `order_name_worker`, `order_company`) VALUES (:order1, :order_name_worker, :worker_company)";
$params = [
"order1" => $item1,
"order_name_worker" => $worker_name,
"worker_company" => $worker_company
];
$dbh->prepare($sql)->execute($params);
}
$order_dishes1 = [];
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
</head>
<body>
<select type="text" name="filter" id="filter">
<option value="*">All</option>
<?php
$sql = "SELECT * FROM `companies`";
$rows = $dbh->query($sql);
foreach ($rows as $row) {
?>
<option value="<?php echo $row['name'] ?>">
<?php echo $row['name'] ?>
</option>
<?php } ?>
</select>
// In this form it works
<form action="thispage.php" method="POST">
<select type="text" name="filter" id="filter">
<option value="*">All</option>
<?php
$sql = "SELECT * FROM `companies`";
$rows = $dbh->query($sql);
foreach ($rows as $row) {
?>
<option value="<?php echo $row['name'] ?>">
<?php echo $row['name'] ?>
</option>
<?php } ?>
</select>
<button type="submit">submit</button>
</form>
<div class="orders__wrapper" id="result">
<?php
$company = $_POST['filter'];
var_dump($_POST['filter']);
$sql = "SELECT * FROM `orders` WHERE `order_company` = '$company'";
$rows = $dbh->query($sql);
foreach ($rows as $row) {
?>
<div class="order-items">
<div class="order-items__header">
<div class="order-items__wrapper">
<div class="order-items__number">
Order №: <?php echo $row['order_id'] ?> </div>
</div>
<div class="order-items__wrapper">
<div class="order-items__name">
<?php echo $row['order_name_worker'] ?> </div>
<div class="order-items__company">
Company:
<span>
<?php echo $row['order_company'] ?>
</span>
</div>
</div>
</div>
<div class="order-items__orders">
<div class="orders-item orders-item-1">
Order №1:
<span class="order1">
<?php echo $row['order_dish1'] ?>
</span>
</div>
</div>
</div>
<?php
$order_dishes1[] = $row['order_dish1'];
}
$content = ob_get_contents();
ob_end_clean();
?>
<div class="result__all" id="result__all">
<div class="result__all-company">
<?php echo $row['order_company'] ?>
</div><br>
<div class="result__all__wrapper">
<div class="result__all-view">
<div class="result__all-title">
Soups:
</div>
<?php
$count_dishes1 = array_count_values($order_dishes1);
foreach ($count_dishes1 as $key => $val) echo '<div class="result__all-item">' . $key . ' - ' . $val . ' шт.,</div>';
?>
</div><br>
</div>
</div>
<?= $content ?>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</body>
</html>

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.

Dynamic Dropdown Menu [PHP]

I'm trying to create a two dropdown that are dynamics, by selecting an option, it changes the other one, just like the Country and Cities examples we see in websites nowadays, but in my case, I want by selecting a Store, it shows all the franquises. I don't know why it's not working.
Here's the code:
<div class="row wow fadeInRight">
<div class="col-sm-3 col-sm-offset-2">
<form action="#">
<div class="form-group">
<label id="drops-labels"><b id="centraliza-txt">Store</b></label>
<span data-toggle="tooltip" data-placement="top" title="Choose a Store">
<?php echo "<select class='form-control input-sm' name='store' id='store-list' onChange='pickFranch(this.value)'>";
echo "<option value='0'>---Select---</option>";
while($dadosRedes = mysql_fetch_array($buscarDadosSuperv)) {
echo "<option value='".$dadosRedes['Store']."'>".$dadosRedes['Store']."</option>";
}
echo "</select>";
?>
</span>
</div>
</form>
</div>
<div class="col-sm-3">
<label id="drops-labels"><b id="centraliza-txt">Franchise</b></label>
<select name="franch" id="franch-list" class='form-control input-sm'">
<option value="0">---Select---</option>
</select>
</div>
<script>
function pickFranch(val) {
$.ajax({
type: "POST",
url: "ajaxPickStore.php",
data: // i dont know what to put here
success: function(data){
$("#lojas-list").html(data);
}
});
}
</script>
AjaxPickStore.php
<?php session_start();
require_once("connect.php");
$db_handle = new DBController();
if(!empty($_POST["store_id"])) {
$query ="SELECT Loja FROM indicadores_rv_m1 WHERE store = '".$_POST['store_id']."' and Supervisor = '".$_SESSION['usuarioNome']."'";
$results = $db_handle->runQuery($query);
?>
<option value="0">---Select---</option>
<?php
foreach($results as $franch) {
?>
<option value="<?php echo $franch["franch"]; ?>"><?php echo $franch["franch"];?></option>
<?php
}
}
?>
I barely know Ajax, so if you could explain the synthax also, it'd help me a lot!
Ty

How to attract parent_id to hidden input codeigniter/ajax

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>

Categories

Resources