select box using ajax and CakePHP - javascript

I'm trying to get data related to parent data from select options , and here's my add.ctp
<select name="id" id="category">
<option value="hide">-- اختر مجموعة الصنف --</option>
<?php foreach ($warehouseCategoriesItems as $warehouseCategoriesItem): ?>
    <option value="<?php echo $warehouseCategoriesItem; ?> " ><?php echo $warehouseCategoriesItem; ?></option>
<?php endforeach; ?>
</select>
<select name="id" id="item">
<option>-- اختر الصنف-- </option>
</select>
and here's the script for that :
<script type="text/javascript">
var types_list = $('#item');
$('#category').change(function(){
carId = $(this).val();
$.ajax({
type: "GET",
url: '../warehouse-add-orders-items-form7/add/' + carId ,
data: { 'carId': carId },
success: function( response ) {
types_list.empty();
types_list.append(
$("<option></option>")
.text('-- إختر نوع --')
.val('')
);
$.each(response, function(id, name) {
types_list.append(
$("<option></option>")
.text(response[id].category_item_name)
.val(response[id].warehouse_categories_items_id)
);
});
types_list.trigger('chosen:updated');
}
});
});
.There's relationship between the category parent and the child items , but i'm getting the child with null values each time and the parent back with it's value .
can any one tell me the problem here ?

Related

Append data working after trigger at third time?

I want to make a dynamic dropdown using selectpicker bootstrap library, codeigniter 4, and AJAX.
I got a problem when I trigger to select the first dropdown, the second dropdown's option appended at third times select. Here I provide the video :
https://youtu.be/AVUBlhajZ_k
Here is my code:
MODEL :
function barangBySupp($namaSupp)
{
$supp = $namaSupp;
$data = $this->db->query("SELECT * FROM tablebarang WHERE supplier='$supp'");
$result = $data->getResultObject();
return $result;
}
CONTROLLER :
public function post()
{
$request = service('request');
if ($request->isAJAX()) {
$namaSupp = $request->getVar('id');
$data = $this->barangMasukModel->barangBySupp($namaSupp);
echo json_encode($data);
}
}
JAVASCRIPT
$("#selectOptSupp").on('changed.bs.select', function(e, clickedIndex, isSelected, previousValue){
const id = $('#selectOptSupp option:selected').data('nama');
const alamat = $('#selectOptSupp option:selected').data('alamat');
const noTelp = $('#selectOptSupp option:selected').data('notelp');
$('[name=namaSupp]').val(id);
$('[name=alamatSupp]').val(alamat);
$('[name=noTelp]').val(noTelp);
$.ajax({
type: "post",
url: "/BarangMasuk/post",
dataType: "JSON",
data: {
id: id
},
cache: false,
success: function(response) {
$.each(response, function(index, data){
$('#selBarang').append('<option data-nama="'+data['namaBarang']+'" data-harga="'+data['harga']+'" data-unit="'+data['unit']+'" value="'+data['namaBarang']+'" data-tokens="'+data['namaBarang']+'">'+data['namaBarang']+'</option>').selectpicker("refresh");
});
SHORT VIEW CODE :
<select id="selectOptSupp" class="form-control selectpicker" data-live-search="true">
<?php foreach ($supplier as $value) : ?>
<option data-nama="<?= $value['namaSupp']; ?>" data-notelp="<?= $value['noTelpSupp']; ?>" data-alamat="<?= $value['alamatSupp']; ?>" data-tokens="<?= $value['namaSupp'] ?>" name="" value="<?= $value['namaSupp'] ?>"><?= $value['namaSupp'] ?>
</option>
<?php endforeach; ?>
</select>
<select id="selBarang" class="form-control selectpicker" data-live-search="true">
// OPTION DATA SHOULD APPEND HERE WHEN #selectOptSupp fires
</select>

Dynamically load second bootstrap selectpicker based on user input of first selectpicker in codeigniter

I want to load data from the database to the second selectpicker based on the input id of the first selectpicker. In the database id of the first selectpicker is the foreign key of the second selectpicker.
View file
1st selectpicker
<select name="depot_select" id="depot_select" class="selectpicker" data-live-search="true" value="<?php echo set_value('depot_select');?>">
<option value="">No Depot Selected</option>
<?php echo $depots['depot'] ?>
</select>
2nd selectpicker
<select class="selectpicker" data-live-search="true" name="route_select" id="route_select" value="<?php echo set_value('route_select');?>">
<option value="">No Route Selected</option>
<?php echo $routes['route']?>
</select>
Ajax
function fetchDepot(){
$.ajax({
type :'POST',
url : '<?php echo base_url('transporter_dashboard/bus/get_depots'); ?>',
dataType: 'json',
success : function(data)
{
$('#depot_select').empty();
var example = $('#depot_select').selectpicker('val', data['data']);
console.log("depot_select" + example);
if(!$.isEmptyObject(data))
{
$.each(data, function(i,o)
{
var depot = $('#depot_select').append('<option value="'+ o['dpt_id'] +'">'+o['dpt_name'] +' </option>');
});
}
$('#depot_select').selectpicker('refresh');
fetchRoute();
},
error: function()
{
alert('error occour..........!');
}
});
}
function fetchRoute()
{
$.ajax(
{
type :'POST',
url :'<?php echo base_url('transporter_dashboard/bus/get_routes'); ?>',
data : { dpt_id : $('#depot_select option:selected').val()},
dataType: 'json',
success : function(data)
{
$('#route_select').empty();
$('#route_select').selectpicker('val', data['data']);
if(!$.isEmptyObject(data))
{
$.each(data, function(i,o)
{
var route = $('#route_select').append('<option value="'+ o['rot_id'] +'">'+ o['rot_name'] +'</option>');
});
}
$('#route_select').selectpicker('refresh');
},
error: function(data){
alert('error occour..........!');
}
});
}
Controller
function get_depots()
{
echo json_encode($this->bus_model->get_depots());
}
function get_routes()
{
if ($this->input->post('dpt_id'))
{
echo json_encode($this->bus_model->get_routes($this->input->post('dpt_id')));
}
}
Model
function get_depots()
{
$this->db->select('*');
$data = $this->db->get('depots')->result_array();
return $data;
}
function get_routes($id)
{
$data = array();
$this->db->select('*');
$this->db->where('dpt_id',$id);
$data = $this->db->get('routes')->result_array();
return $data;
}
According to the above code, only the id of the first option goes to the backend every time despite what option is selected. Then database load only those data which belongs to the id of the first option.
Finally, I found the answer to this question. We need to call fetchRoute() function inside of the $( document ).ready()

Dynamic drop down using single table in codeIgniter

Table
Here when I select Category 1 from drop down I should get district names which comes under Category 1 and for Category 2 I should get districts of Category 2 and so on....
As of now in my code i'm pulling out all district names from my district table master by using district codes. But I should get district names based on category selection.
View:
<select class="form-control" name="category" id='cat_id'>
<?php
foreach($query1 as $row)
{
echo '<option value="'.$row->category.'">'.$row->category.'</option>';
}
?>
</select>
<select name="placename" id="placename">
<?php
foreach($query2 as $row)
{
echo '<option value="'.$row->district_name.'">'.$row-
>district_name.'</option>';
}
?>
</select>
Model:
function viewcatplace()
{
$this->db->select("district.district_name");
$this->db->from('district');
$this->db->join('jc_place_master', 'district.district_code =
jc_place_master.district');
$query = $this->db->get();
return $query->result();
}
Controller:
public function viewcatplace()
{
$this->load->model('JcMeetingExpense_model');
$data['query1'] = $this->JcMeetingExpense_model->viewcatprice();
$data['query2'] = $this->JcMeetingExpense_model->viewcatplace();
$this->load->view('JcMeetingExpense/place_view',$data);
}
You can use this demo for your solution : https://www.codexworld.com/dynamic-dependent-dropdown-codeigniter-jquery-ajax/
It can be only done by ajax:
In controller:
public function index()
{
$web = array();
$web['title'] = 'Select tool';
$web['content'] = 'web/category_index';
// $web['data'] = $this->Common_model->get_all('category','*','','');
$web['data'] = $this->db->query('SELECT DISTINCT category FROM category')->result();
$this->load->view('web_template', $web);
}
Load the category data in select option:
<select class="form-control" id="select_category">
<option value="" disabled selected>Select category</option>
<?php if (isset($data) && !empty($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<option value="<?php echo $value->category; ?>"><?php echo $value->category; ?></option>
<?php endforeach; ?>
<?php endif; ?>
</select>
<select class="form-control" id="append_district"></select>
Using jquery change event get the data using ajax call:
<script type="text/javascript">
$(document).on('change',"#select_category",function (e) {
var optVal= $("#select_category option:selected").val();
if (optVal) {
$.ajax({
type: "post",
url: "getCategoryDetails",
cache: false,
data: {'category' : optVal},
success: function(json){
try {
var obj = jQuery.parseJSON(json);
$('#append_district').empty();
var append_data = '';
if (obj.length > 0) {
$.each(obj, function( index, value ) {
append_data += '<option value="'+value.district+'">'+value.district+'</option>'
});
$('#append_district').append(append_data);
}
} catch(e) {
console.log('Exception while request..');
}
},
error: function(){
console.log('Error while request..');
}
});
}
});
</script>
The data can be get by JSON format.In controller add this method:
public function getCategoryDetails() {
$category = $_POST['category'];
$categoryData = $this->db->query('SELECT district FROM category where category="'.$category.'"')->result();
echo json_encode ($categoryData) ;
}

Choosing a chained select option with jquery using Codeigniter

I'm not much good at jquery and ajax, and I'm now having difficulties on a select box. I use CI and My code is below.
Another select box "category" data will be show according to the "brand". How can I carry data from "brand" and show data in "category" with jquery?
View
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<select name="category" class="form-control" id="category" required>
</select>
Ajax
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var options;
for(var i = 0; i<msg.length; i++) {
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
Controller
function showCategory() {
$brand_id = $this->input->post('brand');
$data['category'] = $this->item_model->category($brand_id);
echo json_encode($data);
}
My category table contains: category_id, category_name, brand_id.
use ajax onchange. .in your view file..
<select name="brand" class="form-control" id="brand" required onchange="brand(this.value,'divid')">
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<div id="divid">
<select name="category" class="form-control" id="category" required>
<option>Select Category</option>
</select>
</div>
<script>
function brand(id,divid)
{
$.ajax({
type: "POST",
data: "pid="+id,
url: '<?php echo base_url(); ?>receiving/showCategory ?>',
success: function(html){
$('#'+divid).html(html);
}
});
}
</script>
in your function showCategory() :
<div id="divid">
<select name="category" class="form-control" id="category" required>
$brandid = $this->input->post('pid');
//you can pass this brand id to your query and echo the category in option value//
<option>//your result //</option>
</select>
</div>
You need to concat the all values in success function like
options += '<option>'+msg.category[i].category_name+'</option'>;
$('#category').html(options);
Look like your code is correct, but need to change a little bit in ajax request.
You need to parse the data return into parseJson first. The options variable in for loop should concatenate with += code. See example below:
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var data = $.parseJSON(msg),options;
for(var i = 0; i<data.length; i++) {
options += '<option>'+data.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
In case you have a problem with this code, you should change variable in codeigniter part for the variable that hold the results. You can see my working code below as an example :
Js Code
$.ajax({
type : 'POST',
url : '<?php echo base_url();?>controller/function_name',
dateType : 'json',
data : {depart_id : _depart_id.val()},
success : function(data){
var json_data = $.parseJSON(data),
options;
for(var i = 0; i<json_data.length; i++){
options += '<option value="'+json_data[i].destination_id+'">'+json_data[i].location+'</option>';
}
_destination_id.html(options);
}
});
Here is codeigniter code(php)
$destination = $this->custom_model->get_destination_distinct($table,$where);
echo json_encode($destination);

Values Are Combining

`I have a script that is returning the right values except for one little problem. Lid is returning 892 which is right, However; Cid which should return 16 its returning 89216 a combination of the two. How can I get Cid to just return 16?
$(document).ready(function()
{
$(".Doggie").change(function()
{
var LocationString ='Lid='+ $(this).val();
$.ajax({
type: "POST",
url: "ajax_city.php",
data: LocationString,
cache: false,
success: function (html) {
$(".Kitty").html(html);
}
});
});
$('.Kitty').live("change",function(){
var Lid = $('#Doggie').val(), // This is the value of the id="Doggie" selected option
Cid = $(this).val(); // This is the value of the id="Kitty" selected option
$.ajax({
type: "POST",
url: "ajax_area.php",
data: {"Lid":Lid,"Cid":Cid},
cache: false,
success: function (html) {
$(".Pig").html(html);
}
});
});
});
</script>
</head>
<body>
<div id="frame1">
<label>Place :</label>
<select name="Doggie" class="Doggie" id="Doggie">
<option selected="selected">--Select Place--</option>
<?php
$sql = mysql_query("SELECT tblLocations.RestID as Lid, tblRestaurants.RestName as name
FROM tblRestaurants INNER JOIN tblLocations ON tblRestaurants.RestID = tblLocations.RestID
GROUP BY tblLocations.RestID, tblRestaurants.RestName
ORDER BY tblRestaurants.RestName ASC");
while($row=mysql_fetch_array($sql))
{
echo '<option value="'.$row['Lid'].'">'.$row['name'].'</option>';
} ?>
</select>
<label>City :</label>
<select name="Kitty" class="Kitty" id="Kitty">
<option selected="selected">--Select City--</option>
</select>
<label>Area: :</label>
<select name="Pig" class="Pig" id="Pig">
<option selected="selected">--Select Area--</option>
</select>
</div>
</body>
</html>
ajax_city.php
<?php
require('config.php');
if($_POST['Lid'])
{
$Lid=$_POST['Lid'];
//$Cid=$_POST['Cid'];
$sql=mysql_query("SELECT tblLocations.RestId as Lid, tblLocations.CityID as Cid, tblCities.CityName as name
FROM tblLocations INNER JOIN tblCities ON tblLocations.CityID = tblCities.CityID
WHERE tblLocations.RestID = $Lid
GROUP BY tblLocations.RestID, tblCities.CityName
ORDER BY tblCities.CityName ASC");
echo '<option selected="selected">--Select City--</option>';
while($row=mysql_fetch_array($sql))
{
echo '<option value="'.$row['Lid'].''.$row['Cid'].'">'.$row['name'].'</option>';
}
}
?>
ajax_area.php
<?php
require('config.php');
if($_POST['Lid'])
{
//$Lid=$_POST['Lid'];
$Cid=$_POST['Cid'];
$sql=mysql_query("SELECT tblLocations.RestId as Lid, tblLocations.CityID as Cid, tblAreas.AreaName as name
FROM tblLocations INNER JOIN tblAreas ON tblLocations.AreaID = tblAreas.AreaID
WHERE tblLocations.RestID = $Lid AND tblLocations.CityID = $Cid
GROUP BY tblLocations.RestID, tblAreas.AreaName
ORDER BY tblAreas.AreaName ASC");
echo '<option selected="selected">--Select Area--</option>';
while($row=mysql_fetch_array($sql))
{
echo '<option value="'.$row['Lid'].''.$row['Cid'].'">'.$row['name'].'</option>';
}
}
?>
It was these two lines in the ajax-city.php file.
"SELECT tblLocations.CityId as Cid, tblCities.CityName as name
And
echo '<option value="'.$row['Cid'].'">'.$row['name'].'</option>';

Categories