Unable to Load Dependent on Multi-Select using PHP and jQuery - php

I tried to load state list multiple selected country and it worked when i tried form here https://phppot.com/php/load-dependent-dropdown-on-multi-select-using-php-and-jquery/
i tried to make some little change by replacing <select> with <input type="checkbox">
but it doesn't load any state list and i get error in console
index.php:36 Uncaught TypeError: Cannot read property 'length' of null
at getState (index.php:36)
at HTMLInputElement.onchange (index.php:64)
getState # index.php:36
onchange # index.php:64
HERE IS WHAT I TRIED:
<div class="row">
<label>Country:</label><br />
<?php
foreach ($countryResult as $country) {
?>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="country[]" id="<?php echo $country["id"]; ?>" onChange="getState();" value="<?php echo $country["id"]; ?>">
<label class="form-check-label" for="<?php echo $country["id"]; ?>">
<?php echo $country["country_name"]; ?>
</label>
</div>
<?php
}
?>
</div>
<div class="row">
<label>State:</label>
<select name="state[]" id="state-list" class="demoInputBox" multiple size=5>
<option value="">Select State</option>
</select>
</div>
SCRIPT
function getState() {
var str = '';
var val = document.getElementById('country-list');
for (i = 0; i < val.length; i++) {
if (val[i].selected) {
str += val[i].value + ',';
}
}
var str = str.slice(0, str.length - 1);
$.ajax({
type: "GET",
url: "get_state.php",
data: 'country_id=' + str,
success: function (data) {
$("#state-list").html(data);
}
});
}
GET_STATE.PHP
<?php
require_once("DBController.php");
$db_handle = new DBController();
if(!empty($_GET['country_id'])) {
$coun_id = $_GET["country_id"];
$query ="SELECT * FROM states WHERE countryID IN ($coun_id)";
$results = $db_handle->runQuery($query);
?>
<option value="">Select State</option>
<?php
foreach($results as $state) {
?>
<option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option>
<?php
}
}
?>
HOW DO I LOAD DATA WITH CHECKBOX INSTEAD OF <select>

try this maybe it helps you
<div class="row">
<label>Country:</label><br />
<?php
foreach ($countryResult as $country) {
?>
<div class="form-check">
<input class="form-check-input country-list" type="checkbox" name="country[]" onChange="getState();" value="<?php echo $country["id"]; ?>">
<label class="form-check-label" for="<?php echo $country["id"]; ?>">
<?php echo $country["country_name"]; ?>
</label>
</div>
<?php
}
?>
</div>
<div class="row">
<label>State:</label>
<select name="state[]" id="state-list" class="demoInputBox" multiple size=5>
<option value="">Select State</option>
</select>
</div>
Script
function getState() {
var str = '';
var val = document.getElementsByClassName('country-list');
for (i = 0; i < val.length; i++) {
if (val[i].checked) {
str += val[i].value + ',';
}
}
var str = str.slice(0, str.length - 1);
$.ajax({
type: "GET",
url: "get_state.php",
data: 'country_id=' + str,
success: function (data) {
$("#state-list").html(data);
}
});
}

Related

Displaying specific data from the database in a dependent select box in Codeigniter

How can I load data from my database into a select box? This select box is dependent to another select box.
I will need to update the details of my products. When I click the specific product in the table, the product details will load on my update view. Everything is almost fine except for one select box namely size select box, which the data didn't show.
I tried many solutions but none of them works.
This is my product table view:
<div class="col-sm-10" id="main">
<div class="table-wrapper">
<div id="content">
<legend class="text-danger"><h1>Product List</h1></legend>
<?php $tableAttr = array(
'table_open' => '<table class="table table-responsive table-striped table-hover" id="item_tbl">',
);
$item_table = $this->table->set_heading('No.','PRODUCT CODE','PRODUCT DESCRIPTION','BRAND', 'CATEGORY', 'SIZE','ORIGINAL PRICE','ACTION');
$item_table = $this->table->set_template($tableAttr);
$num = 0;
foreach ($items as $item) {
$itemName = urlencode($item->prod_desc);
$num++;
$item_table = $this->table->add_row($num, $item->prod_code, $item->prod_desc, $item->brand_name,$item->category_name,$item->size,'₱'. $item->original_price,"
<a href='".base_url("item/update/$itemName")."'><button class='btn btn-info btn-sm'>EDIT</button></a>
");
}
echo $this->table->generate($item_table); ?>
</div>
</div>
</div>
So when I click edit button it will another form the product_update_view.php:
<div class="col-sm-10" id="main" style="padding: 20px;">
<?php echo form_open("item/item_update/$item->prod_id");
echo form_fieldset('<h3 class="text-info">Update Item</h3>'); ?>
<input type="hidden" name="cur_code" value="<?php echo $item->prod_code ?>">
<input type="hidden" name="cur_name" value="<?php echo $item->prod_desc ?>">
<input type="hidden" name="cur_category" value="<?php echo $item->category_name ?>">
<input type="hidden" name="cur_brand" value="<?php echo $item->brand_name ?>">
<input type="hidden" name="cur_size" value="<?php echo $item->size ?>">
<input type="hidden" name="cur_price" value="<?php echo $item->original_price ?>">
<div class="form-group">
<label for='prod_code'>Product Code:</label>
<input type="text" name="up_code" class="form-control" value="<?php echo $item->prod_code; ?>">
</div>
<div class="form-group">
<label for='prod_name'>Product Description:</label>
<input type="text" name=up_name" class="form-control" value="<?php echo $item->prod_desc; ?>">
</div>
<div class="form-group">
<label for='prod_name'>Brand:</label>
<select name="brand" class="form-control">
<option value="Select Brand" selected="selected">Select Brand</option>
<?php foreach($brand as $br):?>
<option value="<?php echo $br->brand_id; ?>" <?php if ($br->brand_id == $item->brand_id) {echo "selected='selected'";} ?>><?php echo $br->brand_name?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label for="category">Category</label>
<select class="form-control" name="category" id="category">
<option value="Select Brand"> Select Category</option>
<?php foreach($category as $cat): ?>
<option value="<?php echo $cat->category_id; ?>" <?php if ($cat->category_id == $item->category_id) {echo "selected='selected'";} ?>><?php echo $cat->category_name; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="sizes">Size:</label>
<select class="form-control" name="category" id="sizes">
<option value="Select size"> Select Size</option>
</select>
</div>
<div class="form-group">
<label for='prod_price'>Price:</label>
<input type="text" name="price" class="form-control" value="<?php echo $item->original_price; ?>">
</div>
<div class="form-group">
<input type="submit" name="submit_account" class="btn btn-primary" value="Save" >
</div>
</div>
<script src="<?php echo base_url() ?>dropdown/js/jquery.js"></script>
<script src="<?php echo base_url() ?>dropdown/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#category').on('change', function(){
var category_id = $(this).val();
if(category_id === '')
$.ajax({
url:"<?php echo base_url() ?>welcome/get_sizes",
type: "POST",
data: {'category_id' : category_id},
dataType: 'json',
success: function(data){
$('#sizes').html(data);
},
error: function(){
alert('Error occur...!!');
}
});
}
});
});
</script>
</div>
<?php echo form_close(); ?>
The controller (item.php):
public function update($name) {
$this->load->model('Dependent_model', 'dep_model', TRUE);
$this->load->model('brand_model');
$data['category'] = $this->dep_model->get_category_query();
$data['brand'] = $this->brand_model->getBrandName();
$this->load->model('item_model');
$data['item'] = $this->item_model->item_info($name);
$this->load->view('header');
$this->load->view('side_menu');
$this->load->view('product_update_view.php',$data);
$this->load->view('footer');
}
The controller of dependent select box (welcome.php):
class Welcome extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Dependent_model', 'dep_model', TRUE);
}
public function index()
{
$data['category'] = $this->dep_model->get_category_query();
$this->load->view('new_product', $data);
}
public function get_sizes()
{
$category_id = $this->input->post('category_id');
$sizes = $this->dep_model->get_sizes_query($category_id);
if(count($sizes)>0)
{
$pro_select_box = '';
$pro_select_box .= '<option value="Select Size">Select Size</option>';
foreach ($sizes as $sz) {
$pro_select_box .='<option value="'.$sz->size_id.'">'.$sz->size.'</option>';
}
echo json_encode($pro_select_box);
}
}
}
Models (item_model.php):
public function item_info ($itemName) {
$this->load->database();
$this->db->select('products.*,category.category_name,sizes.size,brand.brand_name')
->from('products')
->from('category');
$this->db->from('sizes');
$this->db->from('brand');
$this->db->where('products.category_id = category.category_id');
$this->db->where('products.size_id = sizes.size_id');
$this->db->where('products.brand_id = brand.brand_id');
$this->db->where('prod_desc', urldecode($itemName));
$result=$this->db->get();
return $result->row();
}
The dependent select box model (dependent_model):
<?php
class Dependent_model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function get_category_query()
{
$query = $this->db->get('category');
return $query->result();
}
public function get_sizes_query($category_id)
{
$query = $this->db->get_where('sizes', array('category_id' => $category_id));
return $query->result();
}
}
The problem is it does not show the size of the specific product in product_update view.
Replace this jquery.
<script src="<?php echo base_url() ?>dropdown/js/jquery.js"></script>
<script src="<?php echo base_url() ?>dropdown/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var cat_id = $("#category option:selected").val();
if(cat_id != '')
$.fn.ajaxCall(cat_id);
ajaxCall(category_id);
$('#category').on('change', function(){
var category_id = $(this).val();
if(category_id != '')
$.fn.ajaxCall(category_id);
});
$.fn.ajaxCall = function(category_id){
$.ajax({
url:"<?php echo base_url() ?>welcome/get_sizes",
type: "POST",
data: {'category_id' : category_id},
dataType: 'json',
success: function(data){
$('#sizes').html(data);
},
error: function(){
alert('Error occur...!!');
}
});
}
});
</script>

Auto populate text field depending on dropdown using same SQL table

I'm trying to populate a text field and a text area depending on the choice of the second dropdown list using an SQL table. Somehow I got it all wrong. Here's my code right now:
AJAX/HTML
<script>
function getPackage(val) {
$.ajax({
type: "POST",
url: "get_package.php",
data:'serviceid='+val,
success: function(data){
$("#package-list").html(data);
}
});
}
function getPackageDesc(val) {
$.ajax({
type: "POST",
url: "get_packagedesc.php",
data:'packageid='+val,
success: function(data){
$("#price").html(data);
}
});
}
function selectService(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
</script>
I feel like there is already something wrong with function getPackageDesc. I don't know if it's in this function or in the php file.
MAIN HTML
<div class="frmDronpDown">
<div class="row">
<label>Service:</label>
<br/>
<select name="service" id="service-list" class="demoInputBox" onChange="getPackage(this.value);">
<option value="">Select Service</option>
<?php
foreach($results as $service) {
?>
<option value="<?php echo $service[" serviceid "]; ?>">
<?php echo $service["servicename"]; ?>
</option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>Package:</label>
<br/>
<select name="package" id="package-list" class="demoInputBox" onChange="getPackageDesc(this.value);">
<option value="">Select Package</option>
</select>
</div>
<div class="row">
<label>Package Information:</label>
<br/>
<br/> Price:
<br>
<input type="text" name="price" id="price">
<br>
<br> Package Description:
<br>
<textarea name="packagedesc" form="usrform" id="packagedesc"></textarea>
</div>
</div>
get_package.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["serviceid"])) {
$query ="SELECT * FROM tbl_packages WHERE serviceid = '".$_POST["serviceid"]."'";
$results = $db_handle->runQuery($query);
?> < option value = "" > Select Package < /option>
<?php
foreach($results as $package) {
?> < option value = "<?php echo $package["
packageid "]; ?>" > <?php echo $package["packagename"]; ?> < /option>
<?php
}
}
?>
This part of the code works. I have populated the dropdowns using two SQL tables, tbl_services and tbl_packages. The next php file is where I'm having trouble.
get_packagedesc.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["packageid"])) {
$query ="SELECT * FROM tbl_packages WHERE packageid = '".$_POST["packageid"]."'";
$result = mysqli_query($conn, $query);
?>
<?php
while($row = mysqli_fetch_array($result)){
?>
<?php echo $price['price'] ; ?></br>
<?php echo $packagedesc['packagedesc']; ?> </br>
<?php
}
}
?>
This code is where I'm having trouble at. I don't know if it is okay to get data from the same SQL table (tbl_packages). Or maybe I messed up with the $result.
What is wrong with my code and what could be the solution?
Thanks for any help.
It looks like you're not grabbing the information from the row itself but from undeclared variables. Try this:
<?php echo $row['price'] ; ?></br>
<?php echo $row['packagedesc']; ?> </br>

How to append data from database inside text area using PHP and MongoDB

I need to display data inside text area using PHP and MongoDB. Here is my code:
if(st==1){
var data=$.param({'op':'setField','sid':id});
$.ajax({
method:'POST',
url:"dbcon/DBConnection.php",
data:data
}).done(function(msg){
//console.log('question',msg);
var qdata=JSON.parse(msg);
//console.log('question',qdata);
var get =$("#ques").val();
if(get==null || get==''){
alert('Please add no of questions');
}else{
var counter = 0;
if (counter > 0){
return;
}else{
counter++;
<?php
$status=array("status"=>'1');
$feeddata=$db->kf_answertype->find($ustatus);
?>
<?php
$status=array("status"=>'1');
$feeddatascale=$db->kf_scale->find($ustatus);
?>
<?php
$fid=$_GET['ids'];
$data=array();
$mongoid=array('feedback_id'=>$fid);
$ques=$db->kf_questions->find($mongoid);
foreach($ques as $q){
$data[]=$q;
}
?>
for(var i=1;i<get;i++){
$('#container').append('<div><div style="width:24%; float:left; padding:10px;"> <textarea class="form-control" name="questions'+ i +'" id="questions" placeholder="Questions" style="background:#FFFFFF;" rows="2"><?php echo $data[i] ?></textarea></div><div style="float:left;margin-top:37px;"><div style="float:left; margin-right:10px;"><?php foreach($feeddata as $v){?> <input type="radio" name="answer_type'+i+'" id="answer_type0" onClick="selectScale(this.value,'+i+');" value="<?php echo $v['_id']; ?>"> <?php echo $v['answertype']; ?> <?php }?></div><div style="float:left; margin-top:-10px;display:none;" id="scaleid'+i+'"><select class="form-control" id="nscale'+i+'" name="noofscale'+i+'"><option value="">Select Answer Type</option><?php foreach($feeddatascale as $v){ ?><option value="<?php echo $v['_id']; ?>" <?php if($getcustomerobj->no_of_scale == $v['_id'] or $_REQUEST['no_of_scale'] == $v['_id']){ print 'selected'; } ?>><?php echo $v['noofscale']; ?></option><?php } ?></select></div><div style="clear:both;"></div></div><div style="clear:both;"></div></div>');
}
}
}
});
}
Here you can check $data object is containing some value from database and I need to display this $data[$i]->questions like value inside text area which is inside loop.

Codeigniter : Jquery fill the textbox based on combobox

I am Nubie in JQuery especially in ajax..
I have read articles about dropdown combobox (read from database) then fills other textbox (read from database based on combobox data) but I have confused
I Need Jquery / Ajax / something to show it
can someone solve my problem and explain to me..
Controller
public function tambah()
{
$cek = $this->session->userdata('logged_in');
if(empty($cek))
{
header('location:'.base_url().'app_admin');
}
else
{
$d['nama_madrasah'] = "";
$d['nsm'] = "";
$d['provinsi'] = "";
$d['alamat'] = "";
$d['kecamatan'] = "";
$d['kab_kota'] = "";
$d['jenis_bantuan'] = "";
$d['jenjang'] = "";
$d['th_ang'] = "";
$d['sumber_dana'] = "";
$d['tahap_pencairan'] = "";
$d['st'] = "tambah";
$d['dt_nsm'] = $this->app_model->ShowNSMMaster();
$this->load->view("app_admin/madrasah/input",$d);
}
}
My View
<select data-placeholder="Cari NSM..." class="chzn-select" style="width:260px;" tabindex="2" name="nsm" id="dt_nsm" >
<?php
if($st=='edit')
{
?>
<option value="<?php echo '$nsm'; ?>" selected="selected"><?php echo '$nsm'; ?></option>
<?php
}
else
{
?>
<option value="" selected="selected">- Pilih -</option>
<?php
foreach($dt_nsm->result_array() as $dp1)
{
?>
<option value="<?php echo $dp1['nsm']; ?>"><?php echo $dp1['nsm']; ?> | <?php echo $dp1['nama_madrasah']; ?></option>
<?php
}
}
?>
</select>
</span></div>
<label class="control-label" for="nama_madrasah">Nama Madrasah </label>
<div class="controls">
<input type="text" class="span" name="nama_madrasah" id="nama_madrasahx" value="<?php echo $nama_madrasah; ?>" placeholder="">
</div>
<label class="control-label" for="alamat">Alamat</label>
<div class="controls">
<input type="text" class="span" name="alamat" id="alamatx" value="<?php echo $alamat; ?>" placeholder="">
</div>
JS
<script type="text/javascript">
$('#dt_nsm').on('change', function(){
dt_nsm = $('#dt_nsm option:selected').val(); // the dropdown item selected value
$.ajax({
type :'POST',
dataType:'json',
data : { dt_nsm : dt_nsm },
url : 'getresult.php',
success : function(result){
$('#nama_madrasahx).val(result['nama_madrasahx']);
$('#kecamatanx).val(result['kecamatanx']);
}
});});
</script>
getresult.php
<?php
require_once ('../config/db.config.php');
$dt_nsm = $_POST['dt_nsm'];
$query = "SELECT * FROM bantuan WHERE nsm = '$nsm' ";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
echo json_encode($row);
?>
Thanks For your time. Need Advice !
change
foreach($dt_nsm->result_array() as $dp1)
to
foreach($dt_nsm->result_array() as $key=>$dp1)

Display Table based on dropdownlist selection in PHP

My table is not displayed when i select any project name. I guess the onchange function is not working properly but i couldn't figure out the problem.
Code is as follows:
<div class="span6">
<?php $sql = "SELECT * from login_projects WHERE login_id='".$record['login_id']."'";
$res_sql = mysql_query($sql); ?>
<label>Project Name <span class="f_req">*</span></label>
<!--<input type="text" name="city" class="span8" />-->
<select name="project_name" onchange="get_list_onnet()" id="project_name" class="span8">
<option value="">--</option>
<?php while($rec_sql = mysql_fetch_array($res_sql)){ ?>
<option value="<?php echo $rec_sql['project_id']; ?>">
<?php echo $rec_sql['project_name']; ?></option>
<?php } ?>
</select>
</div>
Function:
<script>
function get_list_onnet(){
var project_name=$("#project_name").val();
$.ajax
({
type: "POST",
url: "ajax.php",
data: {action: 'get_list_onnet',list_onnet:project_name},
success: function()
{
document.getElementById("dt_a").style="block";
$("#dt_a").html(html);
}
});
};
</script>
<script>
$(document).ready(function() {
//* show all elements & remove preloader
setTimeout('$("html").removeClass("js")',1000);
});
</script>
Ajax.Php Page:
function get_list_onnet(){
$list_onnet=$_POST['list_onnet'];
$sql_list_onnet=mysql_query("SELECT * from projects,project_wise_on_net_codes
where projects.project_id = project_wise_on_net_codes.project_id AND
project_wise_on_net_codes.project_id='$list_onnet'");
$row1 = mysql_num_rows($sql_list_onnet);
if($row1>0)
{
echo "<tr><th>id</th><th>Project Name</th><th>Country Code</th><th>On-net prefix</th>
<th>Action</th></tr>";
$k = 1; while($row_list_onnet=mysql_fetch_array($sql_list_onnet))
{
$project3 = $row_list_onnet['project_name'];
$countrycode1 = $row_list_onnet['country_code'];
$prefix1 = $row_list_onnet['on_net_prefix'];
$id_proj = $row_list_onnet['project_id'];
$on_prefix = $row_list_onnet['on_net_prefix'];
echo "<tr><td>".$k."</td><td>".$project3."</td><td>".$countrycode1."</td>
<td>".$prefix1."</td><td><a href='process/update_process_onnet.php?ID=".$id_proj."&Onnet=".$on_prefix."'>Delete</a></td>
</tr>";
$k++;
}
}
else
{
echo "<script>alert('No Record Found')</script>";
}
}
The problem is that it is always going in the else condition and nothing is displayed in the table.

Categories