dropdown value is not getting selected ajax html() response - php

I have written a dependable dropdown and its first get the id from the first dropdown and set the div id of the second drop down through ajax call. The issue is when I try to do with html() the second drop down first value can not be selected.
Here is the image of the dependable dropdown
Here is the code I am trying:
<div class="modal fade" id="addNewFloor" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" >
<div class="modal-dialog" role="document" style="">
<div class="modal-content">
<?php echo form_open('registrations/saveNewFloor'); ?>
<?php if (isset($message)) { ?>
<CENTER><h3 style="color:green;">Data inserted successfully</h3></CENTER><br>
<?php } ?>
<div class="modal-header">
<img src="assets/backend/img/floor.png" style="widows:50px;height:50px">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title" id="myModalLabel">Register New Floor</h4>
</div>
<hr class="colorgraph">
<div id="floorModelBox"></div>
<div class="modal-body" style="margin-bottom:2px;padding-top:1px">
<table class="table table-condensed" style="background-color:#F5F5F5;margin-bottom:1px">
<caption><h3><small>Floor Path</small><h3></caption>
<!------- Select Branch --------------------->
<tr><td>Select Branch</td><td >
<select class="form-control" name="branchId_floorModel1" id="branchId_floorModel" onChange="return selectBuildings_floorModel(this.value);selectBuildings_floorModel323();clearFloors();clearSections();clearIots();clearGateways();myFunction();" >
<option value="0" selected> -- select Branch --</option>
<?php
foreach($groups as $row)
{
echo '<option value="'.$row->branchId.'">'.$row->branchName.'</option>';
}
?>
</select></td></tr>
<tr><td>Select Building</td><td>
<select class="form-control" name="buildingBox_floorModel1" style="width:100%;" id="buildingBox_floorModel" required>
<option selected ="selected" value="0">select Building</option></select>
</td></tr>
</table>
<hr/>
<table class="table table-condensed" style="margin-top:2px;margin-bottom:1px">
<caption><h3><small>Floor Details </small><h3></caption>
<tr><td>Floor Name :</td><td > <input type="text" class="form-control input-sm" name="floorName_FloorModel" id="floorName_FloorModel" /></td></tr>
<tr><td>Floor No : </td><td><input type="text" class="form-control input-sm" placeholder="building no" name="floorNo_FloorModel" id="floorNo_FloorModel" /></td></tr>
</table>
</div>
<div class="modal-footer" style="margin-bottom:2px;padding-top:1px">
<hr class="colorgraph">
<button type="button" class="btn btn-primary " data-dismiss="modal" onClick="window.location.reload();">CLOSE</button>
<?php echo form_submit(array( 'class'=>'btn btn-success ', 'id' => 'submit', 'value' => 'Submit')); ?>
<?php echo form_close(); ?><br/>
<div id="fugo">
</div>
</div>
</div>
</div>
</div>
function selectBuildings_floorModel(branchId) {
$.ajax({
url: '<?php echo base_url();?>registrations/get_building_section/' + branchId ,
success: function (response)
{
jQuery('#buildingBox_floorModel').html(response);
}
});
}
//controller method
function get_building_section($branchId)
{
$this->MBuilding->get_building_by_branch($branchId);
$sections = $this->db->get_where('building' , array(
'branchId' => $branchId
))->result_array();
// print_r($sections);die;
foreach ($sections as $row) {
//echo $row['buildingName'];
//
echo '<option value="' . $row['buildingId'] . '">' . $row['buildingName'] . '</option>';
}
}
I even tried with the append() method, but then it's not clearing the dropdown list value.

Try Following...
$("#branchId_floorModel").change(function (){
// Your Code....
});

Related

how to display data in input tag after selecting in select tag value?

I want to achieve after selecting in my select tag, it will display a input tag in my modal and that has been fetch in other table in database.
totalfees.php
if(isset($_POST["year"]))
{
$output = '';
$query = "SELECT total_fees FROM manage_fees WHERE year_lvl = '".$_POST["year"]."'";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$output .= '
<input type="text" class="form-control" id="tf" name="tf" readonly="readonly" value="'.$row["total_fees"].'">
';
}
echo $output;
}
gettotal.js
$(document).ready(function(){
$('#year').click(function(){
var year = $(this).attr("year");
$.ajax({
url:"../include/assessment.php",
method:"post",
data:{year:year},
success:function(data){
$('#total_fees').html(data);
}
});
});
assessment.php
<div class="modal fade" id="fee_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Assess Student</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="POST" action="officer_studentAssessment.php" id="reg">
<div class="form-group">
<label for="year">Year</label>
<select class="form-control" id="year" name="year" required>
<?php
$result = $connect->query("SELECT * FROM year_lvl") or die($connect->error());
while($row = $result->fetch_assoc()):
?>
<option value="<?php echo $row['year']; ?>"><?php echo $row["year"]; ?></option>
<?php endwhile; ?>
</select>
</div>
<div class="form-group" id="total_fees">
<label for="tf">Total fees</label>
</div>
<div class="modal-footer">
<button class="btn btn-success" name="create" id="create" type="submit">Create</button>
</div>
</form>
</div>
</div>
</div>
</div>
in totalfees.php the output should be display on the DIV tag where id = total_fees, the problem is after I click the select tag the DIV disappears
<div class="form-group" id="total_fees">
<label for="tf">Total fees</label>
</div>
add
<scritp>
let selectval = document.getElementById('selectId');
let val =document.getElementById('yourId');
let val.value = selectval
</script>
in slectId add id of your select input and in yourId add id of input field where you would like to add the data
Looks like a wrong-word typo.
In gettotal.js, in your ajax code block, you are calling out to the wrong url.
Instead of:
url:"../include/assessment.php",
try:
url:"../include/totalfees.php",
Also, you might want to change:
$('#year').click(function(){
to
$('#year').change(function(){

How to display a table using AJAX in modal?

officer_cashier.php
This is my modal form I want to display a table upon clicking the button add from cashier_template.php in DIV tag id=add_table
<div class="modal fade" id="fee_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Process payment</h5>
<button type="button" class="close get_close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="POST" action="officer_cashier.php" id="reg">
<fieldset class="scheduler-border">
<legend class="scheduler-border">Student information</legend>
<input type="hidden" class="form-control" id="id" name="id">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" readonly="readonly">
</div>
<div class="form-group">
<label for="course">Course</label>
<input type="text" class="form-control" id="course" name="course" readonly="readonly">
</div>
<div class="form-group">
<label for="sem">Semester</label>
<input type="text" class="form-control" id="sem" name="sem" readonly="readonly">
</div>
<div class="form-group">
<label for="year">Year</label>
<input type="text" class="form-control" id="year" name="year" readonly="readonly">
</div>
</fieldset>
<button class="btn btn-sucess add_fees" id="add_fees">add</button >
<div class="form-group" id="display_table"></div><!-- I want to display the table inside of this DIV tag -->
</form>
</div>
</div>
</div>
</div>
script
This is my AJAX the course,sem,year data is what i need to display the table, so if those three fetch successfully I want to display it in my DIV tag #display_table
$(document).on('click', '.add_fees', function(){
$.ajax({
type: "post",
url: "../templates/cashier_template.php",
data: {
"course": $("#course").val(),
"semester": $("#sem").val(),
"year": $("#year").val(),
},
success: function(data) {
$("#display_table").html(data);
}
});
});
cashier_template.php
This is the cashier template once the AJAX pass the data and matcher the query it should display in modal but I wasnt getting
<?php
ob_start();
include("../include/userlogin.php");
if(!isset($_SESSION))
{
session_start();
}
if($_SESSION['usertype'] != 1){
header("location: login.php?success=1");
$_SESSION['message'] = "You cannot access this page unless you are a officer!";
}
ob_end_flush();
$yearId = $_POST['year'];
$courseId = $_POST['course'];
$semesterId = $_POST['semester'];
$result = $connect->query("SELECT id, total_fees, fee_names FROM manage_fees WHERE year_lvl = '$yearId' AND course = '$courseId' AND semester = '$semesterId'") or die($connect->error());
while($row = $result->fetch_assoc()):
?>
<div class="table-sorting table-responsive" style="margin-top: 1rem;">
<table class="table table-striped table-bordered table-hover" id="table1">
<thead>
<tr class="p-4">
<th scope="col">Select</th>
<th scope="col">School fees</th>
<th scope="col">Amount</th>
<th scope="col">type</th>
</tr>
</thead>
<tbody>
<?php
$result = $connect->query("SELECT * FROM fees;") or die($connect->error());
while($row = $result->fetch_assoc()){
?>
<tr>
<td>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input check_amount" name="local_fees">
<label class="custom-control-label" for="check_amount"></label>
</div>
</td>
<td name="selected_fees"><?php echo $row['fee_name']; ?></td>
<td name="amount"><?php echo $row['amount']; ?></td>
<td><?php echo $row['type']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?php endwhile; ?>
<script src="../js/datable.js"></script>
You are overwriting the $result object (and subsequently the $row obect) when you query fees. So the big loop at the top:
while($row = $result->fetch_assoc()):
is getting overwritten down the line by
$result = $connect->query("SELECT * FROM fees;");
while($row = $result->fetch_assoc()){
But really, there's no need to query FEES in every loop. Why not first get all the fees data into an array, then just access it in the other loop. So first, at the top of your php script:
<?php
$fees=array();
$result = $connect->query("SELECT * FROM fees;");
while($row = $result->fetch_assoc()){ $fees[]=$row; }
?>
Then in your main loop
<?php
foreach ($fees as $fee) {
?>
...
<td name="selected_fees"><?php echo $fee['fee_name']; ?></td>
<td name="amount"><?php echo $fee['amount']; ?></td>
<td><?php echo $fee['type']; ?></td>
</tr>
<?php } ?>

show select checkbox looping from ajax and codeigniter

i want to show checkbox looping from db, if i try to select data id_kendaraan in field then show the data from that id.
this my view code:
<div class="modal fade" id="tambah" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 class="modal-title" id="myModalLabel">Tambah Pemeliharaan</h3>
</div>
<form class="form-horizontal" method="post" action="<?php echo base_url()?>Data/Pemeliharaan/Tambah">
<div class="modal-body">
<div class="form-group">
<label class="control-label col-xs-3">Nama Kendaraan</label>
<div class="col-xs-8">
<select class="form-control" name="id_kendaraan" id="id_kendaraan" required>
<option>Pilih Kendaraan</option>
<?php
if(!empty($kendaraan_)) {
foreach ($kendaraan_ as $isi) {
?>
<option value="<?php echo $isi['id_kendaraan']?>"><?php echo $isi['nama']?> - <?php echo $isi['platno']?></option>
<?php }} ?>
</select>
</div>
</div>
<?php
$index =0;
foreach ($subkriteria_ as $kr_key => $kriteria) {
?>
<div class="form-group">
<label class="control-label col-xs-3"><?php echo $kriteria['nama_kriteria'] ?></label>
<div class="col-xs-8">
<input type="hidden" name="status_pemeliharaan" value="1" class="form-control">
<input type="hidden" name="id_kriteria[]" value="<?php echo $kriteria['id_kriteria'] ?>" class="form-control">
<?php if(!empty($kriteria['sub'])) { ?>
<select class="form-control" name="isi_kriteria[]" required>
<option>Pilih Sub Kriteria</option>
<?php $no = 1; foreach ($kriteria['sub'] as $data) { ?>
<option value="<?php echo $data['value'] ?>"><?php echo $data['namasubkriteria'] ?> - <?php echo $data['value'] ?></option>
<?php $no++; } ?>
</select>
<?php } else if($kriteria['link']=='tahun_beli') { ?>
<input name="isi_kriteria[]" value="" class="form-control" type="text" placeholder="Isi Kriteria..." readonly required>
<?php } else { ?>
<input name="isi_kriteria[]" value="" class="form-control" type="number" placeholder="Isi Kriteria..." required>
<?php } ?>
</div>
</div>
<?php } ?>
<div class="form-group">
<label class="control-label col-xs-3">tes</label>
<div class="col-xs-8">
<input type="checkbox" name="id_sparepart[]" value=""> //my trouble
<input type="text" name="sparepart" value=""> //my trouble
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Tutup</button>
<button class="btn btn-info">Submit</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#id_kendaraan').on('input',function(){
var id_kendaraan=$(this).val();
$.ajax({
type : "POST",
url : "<?php echo base_url('Data/Pemeliharaan/GetKendaraanById')?>",
dataType : "JSON",
data : {id_kendaraan: id_kendaraan},
cache:false,
success: function(data){
$.each(data,function(id_kendaraan, tahun_beli, jenis){
$('[name="isi_kriteria[]"]').val(data.tahun_beli);
$('[name="id_jenis"]').val(data.id_jenis);
$('[name="id_sparepart[]"]').val(data.id_sparepart); //my trouble
$('[name="sparepart"]').val(data.sparepart); //my trouble
});
}
});
return false;
});
});
</script>
on this code, if I select a kendaraan from the select form then data appears according to the selected kendaraan.
it is working, but on the checkbox not show data sparepart for looping from database.
this my controller:
function GetKendaraanById(){
$id_kendaraan=$this->input->post('id_kendaraan');
$data=$this->PemeliharaanModel->GetById($id_kendaraan); ;
echo json_encode($data);
}
i get data from view $id_kendaraan for my parameter.
this my model:
function GetById($id_kendaraan){
$this->db->select('*');
$this->db->from('tb_kendaraan');
$this->db->join('tb_sparepart', 'tb_sparepart.id_jenis = tb_kendaraan.id_jenis');
$this->db->where('tb_kendaraan.id_kendaraan',$id_kendaraan);
$query = $this->db->get();
if($query->num_rows() > 0)
{
foreach ($query->result() as $data) {
$hasil=array(
'tahun_beli' => $data->tahun_beli,
'id_jenis' => $data->id_jenis,
'id_sparepart' => $data->id_sparepart,
'sparepart' => $data->sparepart,
);
}
}
return $hasil;
}
field tahun_beli, id jenis is success to showing in the view.
but the checkbox from sparepart is not looping just show one data.
after selecting the nama kendaraan the checkbox should appear according to the type of kendaraan, data circled in the image should appear more checkbox
thx for helping me
You should separate the query on your model because it has a different format to show (I assume you want to get one kendaraan data with multiple sparepart data) :
function GetById($id_kendaraan){
$this->db->select('*');
$this->db->from('tb_kendaraan');
$this->db->where('tb_kendaraan.id_kendaraan',$id_kendaraan);
$query_kendaraan = $this->db->get();
$hasil = false;
if($query_kendaraan->num_rows() > 0)
{
$data_kendaraan = $query_kendaraan->row();
$hasil = [
'tahun_beli' => $data_kendaraan->tahun_beli,
'id_jenis' => $data_kendaraan->id_jenis,
'spareparts' => [] // empty array, to be filled with spareparts data
];
$this->db->select('*');
$this->db->from('tb_sparepart');
$this->db->where('tb_sparepart.id_jenis', $data_kendaraan->id_jenis);
$query_sparepart = $this->db->get();
foreach ($query_sparepart->result() as $data_sparepart) {
$spareparts = [
'id_sparepart' => $data_sparepart->id_sparepart,
'sparepart' => $data_sparepart->sparepart,
];
array_push($hasil['spareparts'], $spareparts);
}
}
return $hasil;
}
Then on the html side, try to modify the codes like this :
<div class="modal fade" id="tambah" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 class="modal-title" id="myModalLabel">Tambah Pemeliharaan</h3>
</div>
<form class="form-horizontal" method="post" action="<?php echo base_url()?>Data/Pemeliharaan/Tambah">
<div class="modal-body">
<div class="form-group">
<label class="control-label col-xs-3">Nama Kendaraan</label>
<div class="col-xs-8">
<select class="form-control" name="id_kendaraan" id="id_kendaraan" required>
<option>Pilih Kendaraan</option>
<?php
if(!empty($kendaraan_)) {
foreach ($kendaraan_ as $isi) {
?>
<option value="<?php echo $isi['id_kendaraan']?>"><?php echo $isi['nama']?> - <?php echo $isi['platno']?></option>
<?php }} ?>
</select>
</div>
</div>
<?php
$index =0;
foreach ($subkriteria_ as $kr_key => $kriteria) {
?>
<div class="form-group">
<label class="control-label col-xs-3"><?php echo $kriteria['nama_kriteria'] ?></label>
<div class="col-xs-8">
<input type="hidden" name="status_pemeliharaan" value="1" class="form-control">
<input type="hidden" name="id_kriteria[]" value="<?php echo $kriteria['id_kriteria'] ?>" class="form-control">
<?php if(!empty($kriteria['sub'])) { ?>
<select class="form-control" name="isi_kriteria[]" required>
<option>Pilih Sub Kriteria</option>
<?php $no = 1; foreach ($kriteria['sub'] as $data) { ?>
<option value="<?php echo $data['value'] ?>"><?php echo $data['namasubkriteria'] ?> - <?php echo $data['value'] ?></option>
<?php $no++; } ?>
</select>
<?php } else if($kriteria['link']=='tahun_beli') { ?>
<input name="isi_kriteria[]" value="" class="form-control" type="text" placeholder="Isi Kriteria..." readonly required>
<?php } else { ?>
<input name="isi_kriteria[]" value="" class="form-control" type="number" placeholder="Isi Kriteria..." required>
<?php } ?>
</div>
</div>
<?php } ?>
<div class="form-group">
<label class="control-label col-xs-3">tes</label>
<div class="col-xs-8">
<ul id="sparepartList" style="list-style-type: none; padding: 0;"></ul>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Tutup</button>
<button class="btn btn-info">Submit</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#id_kendaraan').on('input',function(){
var id_kendaraan=$(this).val();
$.ajax({
type : "POST",
url : "<?php echo base_url('Data/Pemeliharaan/GetKendaraanById')?>",
dataType : "JSON",
data : {id_kendaraan: id_kendaraan},
cache:false,
success: function(data){
$('#sparepartList').empty(); // clear all sparepart checkboxes
$.each(data, function(id_kendaraan, tahun_beli, jenis){
$('[name="isi_kriteria[]"]').val(data.tahun_beli);
$('[name="id_jenis"]').val(data.id_jenis);
});
$.each(data.spareparts, function (key, value) {
let li = $('<li><input type="checkbox" name="id_sparepart[]" value="' + value.id_sparepart + '" />' +
'<input type="text" name="sparepart" value="' + value.sparepart + '" /></li>');
$('#sparepartList').append(li);
});
}
});
return false;
});
});
</script>
Notice that I changed the sparepart html inputs to an unordered list element, then loop the sparepart data retrieved from the ajax response inside it.
in Your model
$hasil=array(
'tahun_beli' => $data->tahun_beli,
'id_jenis' => $data->id_jenis,
'id_sparepart' => $data->id_sparepart,
'sparepart' => $data->sparepart,
);
U should Store data in $hasil by using []
$hasil[]=array(
'tahun_beli' => $data->tahun_beli,
'id_jenis' => $data->id_jenis,
'id_sparepart' => $data->id_sparepart,
'sparepart' => $data->sparepart,
);

Inserting Data w/ session data into database using Codeigniter

Im having trouble in troubleshooting this problem, I want to save the searched data using input function and pass the id of it into the controller but im having a problem about it,
This is my Controller:
function add($id){
$this->point_m->addStudentSection($id);
redirect('admins_view/points/index');
}
This is my Model:
function addStudentSection($id){
$arr['section_id'] = $this->session->userdata('section_id');
$arr['dateadded'] = $this->input->post('dateadded');
$arr['schoolyear'] = $this->input->post('schoolyear');
$arr['semester'] = $this->input->post('semester');
$arr['point'] = $this->input->post('point');
$this->db->where('student_id',$id);
$this->db->insert('section_student',$arr);
}
in case that model above is wrong here's my other model function that i'am also using, also i am using sqlsrv for my database.
function addStudentSection($id){
$arr['section_id'] = $this->session->userdata('section_id');
$arr['dateadded'] = $this->input->post('dateadded');
$arr['schoolyear'] = $this->input->post('schoolyear');
$arr['semester'] = $this->input->post('semester');
$arr['point'] = $this->input->post('point');
$query = $this->db->query("
INSERT INTO [dbo].[section_student]
([student_id]
,[section_id]
,[dateadded]
,[schoolyear]
,[semester]
,[point])
VALUES
('$id'
,'$section_id'
,'$dateadded'
,'$schoolyear'
,'$semester'
,'$point')
");
}
so in this model i want to use also my section_id which is an session
This is my view :
<table class="table">
<tr>
<th>ID Number</th>
<th>Firstname</th>
<th>Middlename</th>
<th>Lastname</th>
<th>Total Points</th>
<th>Action</th>
</tr>
<?php
foreach ($pt as $p) {
?>
<tr>
<!-- echo query with join -->
<td><?php echo $p->idnumber ?></td>
<td><?php echo $p->firstname ?></td>
<td><?php echo $p->middlename ?></td>
<td><?php echo $p->lastname ?></td>
<td><?php echo $p->point ?></td>
<td>
Add
Redeem
</td>
</tr>
<?php
}
?>
</table>
In this table lies all the searched and retrieve datas from my display function as you can see the button to toggle is a modal.
this is my modal:
<!-- Modal -->
<form method="post" action="<?php echo base_url();?>admins/point/add">
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add Point/s</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<label>Date</label>
<input type="date" name="dateadded" class="form-control">
<label>School year</label>
<select name="schoolyear" class="form-control">
<option value="2018-2019">2018-2019</option>
<option value="2019-2020">2019-2020</option>
</select>
<label>Semester</label>
<select name="semester" class="form-control">
<option value="1st">First Semester</option>
<option value="2nd">Second Semester</option>
<option value="summer">Summer</option>
</select>
<label>Points</label>
<input type="text" name="point" class="form-control">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</form>
and this is the error response..
this is the error
Hope anyone from the community can help me,.
Because your controller add($id) expected 1 parameter, then in modal view you can't set form action like this:
<form method="post" action="<?php echo base_url();?>admins/point/add">
Change your form action to this:
<form method="post" action="<?php echo base_url();?>admins/point/add/$id">
Change $id with your parameter.
Here the docs.
you should add the id at the end of form action in your view.
or you can remove it from your function in controller and post it as a hidden input
so change your view to
<form method="post" action="<?php echo base_url();?>admins/point/add/$id">
or go to your controller and change it to
function add($id = null){
if($id == null){
$id = $this->input->post('id');
}
}
then ad a new hidden input to your view right before form close tag like this
<?php echo form_hidden('id',$the_id);?>

How to pass value from table to bootstrap modal to PHP?

I've fetched rows from MySQL and looped it with Bootstrap modal and I've made a form in modal from which the data is being sent to PHP script (update.php) with the help of ajax. But in return I am getting the output of last row only.
I need to get the record of specific student with its unique ID.
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<table class="table table-responsive">
<thead>
<tr>
<th>NAME</th>
<th>ROLL NUMBER</th>
<th>CONTACT NO</th>
<th>ADDRESS</th>
<th>EDIT</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM students ORDER BY id DESC";
$query_run = mysqli_query($connection, $query);
if($query_run){
while($row = mysqli_fetch_assoc($query_run)){
$id = $row['id'];
$name = $row['name'];
$rollno = $row['rollno'];
$contact = $row['contact'];
$address = $row['address'];
echo "<tr>";
echo '<td>' . $name . '</td>';
echo '<td>' . $rollno . '</td>';
echo '<td>' . $contact . '</td>';
echo '<td>' . $address . '</td>';
echo "<td><button class='btn btn-link btn-custom dis' data-toggle='modal' data-target='#myModal$id'>
EDIT</button> </td>";
echo '</tr>';
?>
<div class="modal fade" id="myModal<?php echo $id; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">EDIT RECORD</h4>
</div>
<div class="modal-body">
<form id="updateValues" action="update.php" method="POST" class="form">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" name="name" id="name" value="<?php echo $name; ?>">
</div>
<div class="form-group">
<label for="rollno">ROLL NO</label>
<input type="text" class="form-control" name="rollno" id="rollno" value="<?php echo $rollno; ?>">
</div>
<div class="form-group">
<label for="contact">CONTACT</label>
<input type="text" class="form-control" name="contact" id="contact" value="<?php echo $contact; ?>">
</div>
<div class="form-group">
<label for="address">ADDRESS</label>
<textarea class="form-control" rows="3" name="address" id="address"><?php echo $address; ?></textarea>
</div>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="submit" class="btn btn-primary btn-custom" value="Save changes">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<div id="results"></div>
</div>
</div>
</div>
</div>
<?php }
}?>
</tbody>
</table>
</body>
</html>
JS:
$(document).ready(function(){
var values, url;
$('#updateValues').submit(function(e){
e.preventDefault();
values = $(this).serialize();
url = $(this).attr('action');
$.post(url, values, function(data){
$('#results').html(data);
});
});
});
Update.php:
<?php
if(isset($_POST['name'])&&isset($_POST['rollno'])&&isset($_POST['contact'])&&isset($_POST['address'])){
$id = $_POST['id'];
$name = $_POST['name'];
$rollno = $_POST['rollno'];
$contact = $_POST['contact'];
$address = $_POST['address'];
echo "$id $name $rollno $contact $address";
}else{
echo 'ERROR!';
}
?>
This is not tested/debugged but refactor your code similar to this:
<?php
$query = "SELECT * FROM students ORDER BY id DESC";
$query_run = mysqli_query($connection, $query);
if($query_run){
$out = '
<table class="table table-responsive">
<thead>
<tr>
<th>NAME</th>
<th>ROLL NUMBER</th>
<th>CONTACT NO</th>
<th>ADDRESS</th>
<th>EDIT</th>
</tr>
</thead>
<tbody>
';
while($row = mysqli_fetch_assoc($query_run)){
$out .= '<tr class="trID_' .$row['id']. '">';
$out .= '<td class="td_name">' . $row['name'] . '</td>';
$out .= '<td class="td_rollno">' . $row['rollno'] . '</td>';
$out .= '<td class="td_contact">' . $row['contact'] . '</td>';
$out .= '<td class="td_address">' . $row['address'] . '</td>';
$out .= "<td><button class='td_btn btn btn-link btn-custom dis'>EDIT</button> </td>";
$out .= '</tr>';
}
$out .= '</tbody></table>
echo $out;
?>
<script>
$(document).ready(){
$('.td_btn').click(function(){
var $row = $(this).closest('tr');
var rowID = $row.attr('class').split('_')[1];
var name = $row.find('.td_name').val();
var rollno = $row.find('.td_rollno').val();
var contact = $row.find('.td_contact').val();
var address = $row.find('.td_address').val();
$('#frm_id').val(rowID);
$('#frm_name').text(name);
$('#frm_rollno').text(rollno);
$('#frm_contact').text(contact);
$('#frm_address').text(address);
$('#myModal').modal('show');
});
});//END document.ready
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">EDIT RECORD</h4>
</div>
<div class="modal-body">
<form id="updateValues" action="update.php" method="POST" class="form">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" name="name" id="frm_name">
</div>
<div class="form-group">
<label for="rollno">ROLL NO</label>
<input type="text" class="form-control" name="rollno" id="frm_rollno">
</div>
<div class="form-group">
<label for="contact">CONTACT</label>
<input type="text" class="form-control" name="contact" id="frm_contact">
</div>
<div class="form-group">
<label for="address">ADDRESS</label>
<textarea class="form-control" rows="3" name="address" id="frm_address"></textarea>
</div>
<input type="hidden" name="frm_id">
<input type="submit" class="btn btn-primary btn-custom" value="Save changes">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<div id="results"></div>
</div>
</div>
</div>
</div>
<?php
}
}
?>
Notes:
(1) Create the entire table in a variable, then output the variable all at once.
(2) You only need one modal, not one modal for each table row. Therefore, remove modal creation from inside while loop.
(3) Use jQuery to:
(a) detect button click in row
(b) get table data for that row
(c) populate fields in modal
(d) display modal
You are using Bootstrap, which uses jQuery, so it makes sense to use jQuery to do this.
(4) Using jQuery to get values from table cells vs. input fields:
(a) .text() - from table cells
(b) .val() - from <input> or <textarea>
Here is a jsFiddle Demo you can play with that demonstrates how you can use jQuery to populate the modal depending on the row that was clicked.

Categories