Codeigniter : Jquery fill the textbox based on combobox - php

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)

Related

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

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

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>

php dropdown show selected but one value by defaut

i'm using php for stored procedure on sql server. My problems is that i would like to show one value by defaut on the dropdown, but when someone select something else and the page refresh, it must show the what that person choose, not the default one. Here what i had done until now :
<form method="post">
<label for="from"><b>De:</b></label>
<input data-date-format='yy-mm-dd' type="text" id="from" name="from" size="6" value="<?php if(isset($_POST['from'])){ echo $_POST['from']; } ?>";/>
<label for="to"><b>A:</b></label>
<input data-date-format='yyyy-mm-dd' type="text" id="to" name="to" size="6" value="<?php if(isset($_POST['to'])){ echo $_POST['to']; } ?>";/>
<label for="group"><b>Groupe:</b></label>
<select type= "text" name="group" id="group" value="";>
<option><?php if(isset($_POST['group'])){ echo $_POST['group']; } ?></option>
<?php
$sql = " Get_List_ReportStation";
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
?>
<option selected value="RAL"><?php echo ($row['F1000'] . " " . $row['F1018']); ?></option>
<?php
}
?>
</select>
<input type="submit" value="Valider" name="submit">
</form>
<?php
if(isset($_POST["submit"])) {
$from = $_POST["from"];
$to = $_POST["to"];
$group = $_POST["group"];
}
?>
Any ideas to help me? Thank you!
<select class="group">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
<option value="test4">test4</option>
</select>
Add Javascript to store the users last value into localstorage.
var select = document.querySelector(".group");
var selectOption = select.options[select.selectedIndex];
var lastSelected = localStorage.getItem('select');
if(lastSelected) {
select.value = lastSelected;
}
// sets up a onselected
select.onchange = function () {
lastSelected = select.options[select.selectedIndex].value;
console.log(lastSelected);
localStorage.setItem('select', lastSelected);
}
Source: How to use LocalStorage on last HTML select value
For your given code try this
<form method="post">
<label for="from"><b>De:</b></label>
<input data-date-format='yy-mm-dd' type="text" id="from" name="from" size="6" value="<?php if(isset($_POST['from'])){ echo $_POST['from']; } ?>";/>
<label for="to"><b>A:</b></label>
<input data-date-format='yyyy-mm-dd' type="text" id="to" name="to" size="6" value="<?php if(isset($_POST['to'])){ echo $_POST['to']; } ?>";/>
<label for="group"><b>Groupe:</b></label>
<select type= "text" name="group" id="group">
<option><?php if(isset($_POST['group'])){ echo $_POST['group']; } ?></option>
<?php
$sql = " Get_List_ReportStation";
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
?>
<option value="<?php echo ($row['F1000']."_".$row['F1018']); ?>"><?php echo ($row['F1000'] . " " . $row['F1018']); ?></option>
<?php
}
?>
</select>
<input type="submit" value="Valider" name="submit">
</form>
<script>
var select = document.querySelector(".group");
var selectOption = select.options[select.selectedIndex];
var lastSelected = localStorage.getItem('select');
if(lastSelected) {
select.value = lastSelected;
} else {
select.value = 'RAL'; // new code
}
// sets up a onselected
select.onchange = function () {
lastSelected = select.options[select.selectedIndex].value;
console.log(lastSelected);
localStorage.setItem('select', lastSelected);
}
</script>
<?php
if(isset($_POST["submit"])) {
$from = $_POST["from"];
$to = $_POST["to"];
$group = $_POST["group"];
}
?>

How to keep form items selected after post request.Using onchange

I have a problem when submit form value from the second select don't show. Can someone explain me what I'm doing wrong because in new in this (maybe is because i use onchange event). Thanks in advance.
index.php
<?php
include("includes/conn.php");
$sql = "SELECT * FROM opstina";
$result = $conn->query($sql);
if($result->num_rows > 0){
$opstineArr = array();
while($row = $result->fetch_assoc()){
$opstineArr[] = $row;
}
}
if(isset($_POST["addNesto"])){
$opstine = $_POST["opstine"];
$ime = $_POST["ime"];
if(isset($opstine)){
if(empty($opstine)){
$error["opstine"] = "izaberite opstinu";
}
}
$naselja = $_POST["naselja"];
if(isset($naselja)){
if(empty($naselja)){
$error["naselja"] = "izaberite naselje";
}
}
if(isset($ime)){
if(empty($ime)){
$error["ime"] = "izaberite ime";
}
}
if(count($error) == 0){
echo 2222;
}
}
include("includes/header.php");
?>
<form action="" method="POST">
<select name="opstine" class="form-control" id="select_id" onchange="getNaselja(this.value)">
<option>..Izaberite Opstinu..</option>
<?php foreach($opstineArr as $key => $opstina): ?>
<option value="<?php echo $opstina['OpstinaID']; ?>" <?php if(isset($opstine) && $opstine==$opstina['OpstinaID']) echo "selected"; ?> ><?php echo $opstina['NazivOpstine']; ?></option>
<?php endforeach; ?>
</select>
<?php if(isset($error["opstine"])) echo $error["opstine"]; ?>
<p>
<select name='naselja' id='naseljeLista' class='form-control' style='margin-top:10px;'>
</select>
<span><?php if(isset($error["naselja"])) echo $error["naselja"]; ?></span>
</p><br>
<input type="text" name="ime" value="<?php if(isset($ime)) echo $ime; ?>" class="form-control col-md-7 col-xs-12"><?php if(isset($error["ime"])) echo $error["ime"]; ?><br><br>
<input type="submit" name="addNesto" class="btn btn-sm btn-success">
</form>
<?php include("includes/footer.php"); ?>
getNaselja.php
global $conn;
include("includes/conn.php");
if(!empty($_POST["opstina_id"])){
$opstinaID = $_POST["opstina_id"];
$sql1 = "SELECT * FROM naselje WHERE OpstinaID=".$opstinaID;
$result1 = $conn->query($sql1);
if($result1->num_rows > 0){
$naseljaArr = array();
while ($one = $result1->fetch_assoc()) {
$naseljaArr[] = $one;
}
}
echo "<option value=''>---Izaberite naselje---</option>";
foreach ($naseljaArr as $key => $value) {
if(isset($_POST["naselja"]) && $value["NaseljeID"]==$_POST["naselja"]){
echo "<option value='".$value['NaseljeID']."' selected='selected' style='display:block;'>".$value['NazivNaselja']."</option>";
}else{
echo "<option value='".$value['NaseljeID']."'>".$value['NazivNaselja']."</option>";
}
}
}
footer.php
<script>
function getNaselja(val){
$.ajax({
type: 'POST',
url: 'getNaselja.php',
data: 'opstina_id='+val,
success: function(data){
$('#naseljeLista').html(data);
console.log(data);
}
});
}
</script>
example of form after submit on index.php
When I choose from first select my data on the console looks like:
<option value=''>---Izaberite naselje---</option>
<option value='4610'>Beška</option>
<option value='4611'>Inđija</option>
<option value='4612'>Jarkovci</option>
<option value='4613'>Krčedin</option>
<option value='4614'>Ljukovo</option>
<option value='4615'>Maradik</option>
<option value='4616'>Novi Karlovci</option>
<option value='4617'>Novi Slankamen</option>
<option value='4618'>Slankamenački Vinogradi</option>
<option value='4619'>Stari Slankamen</option>
<option value='4620'>Čortanovci</option>

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>

Categories