Pass data from bs modal to cloned input fields - php

So i have this issue trying to pass data from bs modal to form inputs, the logic is when i type in first row and press enter a bs modal pops up and show data from database in a table every row has its respective select button so when i click select the chosen row fills up the input fields in the form but after cloning the next rows of inputs and repeat the steps to fill the form from bs modal this only updates all of the fields with same data
Here is an image of the issue
here's my code i've been stuck here for days..
<script>
$(document).ready(function() {
$(".card").on('keyup', '.live_search', function() {
var input = $(this).val();
if (input != "") {
$.ajax({
type: "POST",
url: "livesearch.php",
data: {
input: input
},
success: function(data) {
$(".searchresult").html(data);
$(".searchresult").css("display", "block");
}
});
} else {
$(".searchresult").css("display", "none");
}
});
$(".add-row").click(function(e) {
e.preventDefault();
$("#show-item").prepend(`<tr>
<input type="hidden" name="id[]">
<td class="col-2">
<div class="input-group input-group-sm">
<a href="#" class="btn btn-danger delete-row"> <i class="fa-solid fa-trash-can"></i>
</a>
<input type="text" class="form-control live_search" name="material_name[]" placeholder="Nombre Material">
</div>
</td>
<td class="col-1">
<div class="input-group input-group-sm ">
<input type="text" class="form-control" name="measure_one[]">
</div>
</td>
<td class=" col-1">
<div class="input-group input-group-sm ">
<input type="text" class="form-control" name="measure_two[]">
</div>
</td>
<td class=" col-2">
<div class="input-group input-group-sm ">
<input type="text" class="form-control" name="unit_measure[]">
</div>
</td>
<td class=" col-1">
<div class="input-group input-group-sm ">
<input type="text" class="form-control" name="length[]">
</div>
</td>
<td class=" col-1">
<div class="input-group input-group-sm ">
<input type="text" class="form-control" name="width[]">
</div>
</td>
<td class=" col-1">
<div class="input-group input-group-sm">
<input type="text" class="form-control" name="price[]">
</div>
</td>
</tr>`);
});
// remove product row
$('.card').on('click', '.delete-row', function(evt) {
evt.preventDefault();
$(this).closest('tr').remove();
});
// modal pops up when pressing enter
$('.card').on('keyup', '.live_search', function(e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode == '13') {
// $('.modal').modal('show');
var product = $(this);
$('#insert').modal('show', {
backdrop: 'static',
keyboard: false
}).on('click', '#selected', function(e) {
var id = $(this).attr('data-material-id');
var material = $(this).attr('data-material-name');
var measure_one = $(this).attr('data-material-measure_one');
var measure_two = $(this).attr('data-material-measure_two');
var unit_measure = $(this).attr('data-material-unit_measure');
var length = $(this).attr('data-material-length');
var width = $(this).attr('data-material-width');
var price = $(this).attr('data-material-price');
$(product).closest('tr').find('[name="supplier_id[]"]').val(id);
$(product).closest('tr').find('[name="material_name[]"]').val(material);
$(product).closest('tr').find('[name="measure_one[]"]').val(measure_one);
$(product).closest('tr').find('[name="measure_two[]"]').val(measure_two);
$(product).closest('tr').find('[name="unit_measure[]"]').val(unit_measure);
$(product).closest('tr').find('[name="length[]"]').val(length);
$(product).closest('tr').find('[name="width[]"]').val(width);
$(product).closest('tr').find('[name="price[]"]').val(price);
$('#insert').modal('hide');
});
return false;
}
});
});
</script>
if (mysqli_num_rows($result) > 0) { ?>
<table class="table table-bordered table-striped table-hover table-sm text-center">
<thead class="table-primary">
<tr>
<th>ID</th>
<th>Proveedor</th>
<th>Material</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<?php while ($row = mysqli_fetch_assoc($result)) :
$id = $row['supplier_id'];
$supplier = $row['supplier'];
$material = $row['material'];
?>
<tr>
<td><?php echo $id ?></td>
<td><?php echo $supplier ?></td>
<td><?php echo $material ?></td>
<td>
<?php echo '<a href="#" class="btn btn-link" id="selected" datamaterial-id="' . $row['supplier_id'] . '"
data-material-name="' . $row['material'] . '" data-material-measure_one="' . $row['measure_one'] . '"
data-material-measure_two="' . $row['measure_two'] . '" data-material-unit_measure="' . $row['unit_measure'] . '"
data-material-length="' . $row['length'] . '" data-material-width="' . $row['width'] . '"
data-material-price="' . $row['price'] . '">Select</a>';
?>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

This row in the last keyup eventlistener
var product = $(this);
will select every row.
Try this instead:
var product = $(e.target);
Read more about event.target here.

Related

Editing table data using php, PDO, and Ajax

I have a data table that displays the counter table in the database.
It has create and edit buttons, each linked to a pop-up modal. The create button works fine, but I'm having an issue with the edit button.
When I click the edit button in a row, it's supposed to retrieve the data from the database table and display them in the text fields of the edit modal.
The data gets retrieved without any issues. But, the only thing that gets displayed in the edit modal is the id. The rest of the data gets displayed in the create modal.
I tried to find the error but I couldn't figure it out yet.
This is the counter table
CREATE TABLE IF NOT EXISTS `counter` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`created_at` date DEFAULT NULL,
`updated_at` date DEFAULT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
Here's how the code goes.
create modal
<div id="addModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add New Counter</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<form action="" method="post" id="form-data" novalidate>
<div class=" form-group">
<label>Counter Name</label>
<input type="text" name="name" id="name" class="form-control" required>
</div>
<div class=" form-group">
<label>Description</label>
<textarea name="desc" id="desc" class="form-control" rows="4" cols="50" required></textarea>
</div>
<div class="form-group">
<label>Status</label><br>
<input type="radio" id="status" name="status" value="1" checked required>
<label for="avtive">Active</label><br>
<input type="radio" id="status" name="status" value="0">
<label for="avtive">Inactive</label><br>
</div>
<div class="form-group">
<input type="reset" class="btn btn-secondary" />
<input type="submit" id="insert" name="insert" value="Add Counter" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
</div>
edit modal
<div id="editModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Counter</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<form action="" method="post" id="edit-form-data" novalidate>
<input type="text" name="id" id="id">
<div class=" form-group">
<label>Counter Name</label>
<input type="text" name="name" id="name" class="form-control" required>
</div>
<div class=" form-group">
<label>Description</label>
<textarea name="desc" id="desc" class="form-control" rows="4" cols="50" required></textarea>
</div>
<div class="form-group">
<label>Status</label><br>
<input type="radio" id="status" name="status" value="1" checked required>
<label for="avtive">Active</label><br>
<input type="radio" id="status" name="status" value="0">
<label for="avtive">Inactive</label><br>
</div>
<div class="form-group">
<input type="reset" class="btn btn-secondary" />
<input type="submit" id="update" name="update" value="Edit Counter" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
</div>
script
<script>
$(document).ready(function() {
//edit ajax request
$("body").on("click", ".editBtn", function(e) {
// console.log("working");
e.preventDefault();
edit_id = $(this).attr('id');
$.ajax({
url: "../../php/admin-action.php",
type: "POST",
data: {
edit_id: edit_id
},
success: function(response) {
data = JSON.parse(response);
// console.log(data);
$("#id").val(data.id);
$("#name").val(data.name);
$("#desc").val(data.description);
$("#status").val(data.status);
},
error: function(response) {
toastr.error('Error detected while adding, Please try again later!');
}
})
})
// update ajax request
$("#update").click(function(e) {
if ($("#edit-form-data")[0].checkValidity()) {
e.preventDefault();
$.ajax({
url: "../../php/admin-action.php",
type: "POST",
data: $("#edit-form-data").serialize() + "&action=update",
success: function(response) {
toastr.success('Counter edited successfully!');
setInterval(2000);
$("#editModal").modal('hide');
$("#edit-form-data")[0].reset();
showAllCounters();
},
error: function(response) {
toastr.error('Error detected while editing, Please try again later!');
}
})
}
})
});
</script>
admin-action.php
// handle view counter list
if (isset($_POST['action']) && $_POST['action'] == 'view') {
$output = '';
$data = $db->read_counter();
if ($db->totalRowCount_counter() > 0) {
$output .= '<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Counter</th>
<th>Description</th>
<th>Created Date</th>
<th>Updated Date</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>';
foreach ($data as $row) {
$output .= ' <tr>
<td>' . $row['id'] . '</td>
<td>' . $row['name'] . '</td>
<td>' . $row['description'] . '</td>
<td>' . $row['created_at'] . '</td>
<td>' . $row['updated_at'] . '</td>
<td>' . $row['status'] . '</td>
<td class="project-actions text-right">
<a class="btn btn-primary btn-sm viewBtn" id="' . $row['id'] . '">
<i class="fas fa-folder">
</i>
View
</a>
<a class="btn btn-info btn-sm editBtn" data-toggle="modal" data-target="#editModal" id="' . $row['id'] . '">
<i class="fas fa-pencil-alt">
</i>
Edit
</a>
<a class="btn btn-danger btn-sm dltBtn" id="' . $row['id'] . '">
<i class="fas fa-trash">
</i>
Delete
</a>
</td></tr>';
}
$output .= '</tbody></table>';
echo $output;
} else {
echo '<h3 class="text-center text-secondary mt-5">:(No counters present in the database!)</h3>';
}
// print_r($data);
}
if (isset($_POST['action']) && $_POST['action'] == 'insert') {
$name = $_POST['name'];
$desc = $_POST['desc'];
$status = $_POST['status'];
$db->insert_counter($name, $desc, $status);
}
if (isset($_POST['edit_id'])) {
$id = $_POST['edit_id'];
$row = $db->getCounterByID($id);
echo json_encode($row);
}
if (isset($_POST['action']) && $_POST['action'] == 'update') {
$id = $_POST['id'];
$name = $_POST['name'];
$desc = $_POST['desc'];
$status = $_POST['status'];
$db->update_counter($id, $name, $desc, $status);
}
admin-db.php
public function getCounterById($id)
{
$sql = "SELECT * FROM counter WHERE id = $id";
$stmt = $this->conn->prepare($sql);
$stmt->execute(['id' => $id]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;
}
public function update_counter($id, $name, $desc, $status)
{
$sql = "UPDATE counter SET name=:name, desc=:desc,status=:status WHERE id = :id ";
$stmt = $this->conn->prepare($sql);
$stmt->execute(['name' => $name, 'desc' => $desc, 'status' => $status, 'id' => $id]);
return true;
}
I'm posting all of the code because I'm not exactly sure where the problem is. Apologies for making it so long.
FIRST OF ALL
You should not use the same value for HTML id attribute. You used in both create and edit form the same ids for the input fields. The value of the id attribute has to be unique on the entire HTML page, even if some parts are hidden.
CURRENT BEHAVIOR
Your create form does not have an input field with attribute id='id', that is why the corresponding input field is filled after the ajax request.But the other 4 input fields exist in both forms. Because the create form is placed before the update form in your HTML content, the input fields of create form are filled.
SOLUTION
Please change your success function of your .editBtn click handler like this:
success: function(response) {
data = JSON.parse(response);
// console.log(data);
let $form = $('#edit-form-data');
let radioId = data.status === "1" ? "#editStatusActive" : "#editStatusInactive";
$form.find("input[id='id']").val(data.id);
$form.find("input[name='name']").val(data.name);
$form.find("[name='desc']").val(data.description);
$form.find(radioId).click();
},
},
Then update the form group for status in your update form like this:
<div class="form-group">
<label>Status</label><br>
<input type="radio" name="status" id="editStatusActive" value="1" checked required>
<label for="editStatusActive">Active</label><br>
<input type="radio" name="status" id="editStatusInactive" value="0">
<label for="editStatusInactive">Inactive</label><br>
</div>

Ajax wont stop if false

I have problem with my ajax,
here my index:
<form name="add_name" id="add_name">
<div class="col-lg-12">
<div class="form-row mb-2">
ID Kurir :
<div class="col">
<input type="text" id="idkurir" name="idkurir" placeholder="Input ID Kurir" class="idkurir" autofocus />
</div>
Nama Kurir :
<div class="col">
<input type="text" id="namakurir" name="namakurir" value="Nama Kurir" class="namakurir" readonly />
</div>
No Laporan :
<div class="col">
<input type="text" id="nolaporan" name="nolaporan" value="No Laporan" readonly />
</div>
Date :
<div class="col">
<?php $now=date('d-m-Y H:i'); ?>
<input type="text" name="date" value=<?php echo "'$now'"; ?> readonly />
</div>
</div>
<div class="row">
<div class="col-lg-6">
<table class="table table-bordered" id="dynamic_field1">
<tr>
<td colspan=2 align=center><strong>Antar Ulang</strong></td>
</tr>
<tr>
<td><input type="text" name="awbau[]" placeholder="Enter AWB" class="form-control name_listau" /></td>
<td><button type="button" name="addau" id="addau" class="btn btn-success">Add More</button></td>
</tr>
</table>
</div>
<div class="col-lg-6">
<table class="table table-bordered" id="dynamic_field2">
<tr>
<td colspan=2 align=center><strong>Undelivery</strong></td>
</tr>
<tr>
<td><input type="text" name="awbundel[]" placeholder="Enter AWB" class="form-control name_listundel" /></td>
<td><button type="button" name="addundel" id="addundel" class="btn btn-success">Add More</button></td>
</tr>
</table>
</div>
</div>
<center><input type="button" name="submit" id="submit" class="btn btn-info btn-block mb-4 mr-2" value="Submit Data" /></center>
</form>
here my ajax script :
$(document).on("keypress", ".idkurir", function(e) {
var idkurir = $('#idkurir').val();
if (e.which == 13) {
$.ajax({
type: "POST",
url: "checkdata.php",
data: {
idkurir: idkurir
},
success: function(response) {
if (response == 1) {
alert("Kurir sudah laporan");
} else {
if (response == "ID Kurir tidak di temukan") {
alert(response);
} else {
var d = new Date();
var today_date = ("0" + d.getDate()).slice(-2) + ("0" + (d.getMonth() + 1)).slice(-2);
$('#nolaporan').val(idkurir + today_date);
$('#namakurir').val(response);
}
}
}
});
}
});
and here my checkdata to check if data exist :
session_start();
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("reportchecker", $connect);
$idkurir = $_POST["idkurir"];
$nolaporan = $idkurir . date("dm");
$sql = "SELECT * FROM jampulang WHERE nolaporan = '$nolaporan'";
$result = mysql_query($sql, $connect);
$count = mysql_num_rows($result);
$response = [];
$sql2 = "SELECT * FROM kurir WHERE idkurir = '$idkurir'";
$result2 = mysql_query($sql2, $connect) or die(mysql_error());
$count2 = mysql_num_rows($result2);
if ($count == 1) {
echo "1";
} else if ($count2 == 1) {
$row = mysql_fetch_array($result2) or die(mysql_error());
echo $row['nama'];
} else {
echo "ID Kurir tidak di temukan";
}
my problem is when response from checkdata = "ID Kurir tidak di temukan", ajax not showing alert and stop update field nolaporan and nama kurir
$('#nolaporan').val(idkurir + today_date);
$('#namakurir').val(response);
in my script above when reponse "ID Kurir tidak di temukan" still update field nolaporan and namakurir.
You can fix it on the client side using $.trim() like below:
if($.trim(response) == 'ID Kurir tidak di temukan') {
//do your code
}

how to update with modal bootstrap and checkbox

hey guys how can i update multiple rows with checkbox and display modal bootstrap after pressing update button?
example like this:
I checked the line with the checkbox
After that I press "Pindah Department" or in english "Move Departemen"
actually I do not need the edit book () function, I only need one function and the funtion it can call modal bootstrap pops up, to update from the dropdown menu"
i forgot to change save button to call function prepareData(), pop up appears, but I do not know what it is
I can only edit it one by one, with Modal Bootstrap, how can i be like above that?
this is my view:
<table id="emp_id" class="table table-bordered dt-responsive" cellspacing="0" width="100%">
<thead>
<tr>
<th width="1%" align="center"><input type="checkbox" onClick="toggle(this)" id="checkAll" name="checkAll" /></th>
<th width="1%" align="center">No.</th>
<th width="1%" align="center">Edit</th>
<th width="20%" align="center">Nama Lengkap</th>
<th width="5%" align="center">No Induk</th>
<th width="10%" align="center">Jenis Kelamin</th>
<th width="5%" align="center">PIN</th>
<th width="20%" align="center">Departemen</th>
</tr>
</thead>
<tbody>
<?php
foreach($data as $d){
?>
<tr>
<td>
<input class="childbox" width="1%" type="checkbox" name="msg[]" id="id" align="center" value="<?php echo $d['emp_id'] ?>" />
</td>
<td width="1%" align="center"><?php echo $d['emp_id']; ?></td>
<td><button class="btn btn-light" onclick="edit_book(<?php echo $d['emp_id'];?>)"><i class="glyphicon glyphicon-pencil"></i></button></td>
<td class="data-check"><?php echo $d['first_name']; ?></td>
<td class="data-check"><?php echo $d['nik']; ?></td>
<td class="data-check"><?php echo $d['gender']=='0' ? 'Laki-Laki' : 'Perempuan'; ?></td>
<td class="data-check"><?php echo $d['pin']; ?></td>
<td class="data-check"><?php echo $d['dept_name']; ?></td>
</tr>
<?php } ?>
</tbody>
<tfoot>
<tr>
<th width="1%" align="center"><input type="checkbox" onClick="toggle(this)" id="checkAll" name="checkAll" /></th>
<th width="1%" align="center">No.</th>
<th width="1%" align="center">Edit</th>
<th width="20%" align="center">Nama Lengkap</th>
<th width="5%" align="center">No Induk</th>
<th width="10%" align="center">Jenis Kelamin</th>
<th width="5%" align="center">PIN</th>
<th width="20%" align="center">Departemen</th>
</tr>
</tfoot>
</table>
this is my script to bring up modal bootstrap and for checkbox functions:
<script type="text/javascript">
$(document).ready( function () {
$('#emp_id').DataTable( {
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
} );
$("input[name='checkAll']").click(function() {
var checked = $(this).attr("checked");
$("#emp_id tr td input:checkbox").attr("checked", checked); });
} );
function toggle(id) {
checkboxes = document.getElementsByName('msg[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = id.checked;
}
}
function add_book()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('#modal_form').modal('show'); // show bootstrap modal
//$('.modal-title').text('Add Person'); // Set Title to Bootstrap modal title
}
function edit_book(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('proses/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="emp_id"]').val(data.emp_id);
$('[name="dept_id_auto"]').val(data.dept_id_auto);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Departemen'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('proses/book_add')?>";
}
else
{
url = "<?php echo site_url('proses/book_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
</script>
and this is my modal bootstrap :
<div id="modal_form" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<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">Tambah Siswa</h4>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="emp_id"/>
<div class="form-body">
<div class="form-group">
<label for="colFormLabelLg" class="col-sm-4 col-form-label col-form-label-lg">Pilih Departemen Baru</label>
<div class="col-sm-6">
<select name="dept_id_auto" class="form-control pull-right">
<?php
foreach($groups as $row)
{
echo '<option name="dept_id_auto" value="'.$row['dept_id_auto'].'">'.$row['dept_name'].'</option>';
}
?>
</select>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-info" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
and this is my controller :
public function book_update()
{
$data = array(
'dept_id_auto' => $this->input->post('dept_id_auto'),
);
$this->Pindah_dept_model->book_update(array('devid_auto' => $this->input->post('devid_auto')), $data);
echo json_encode(array("status" => TRUE));
}
public function ajax_edit($id)
{
$data = $this->Pindah_dept_model->get_by_id($id);
echo json_encode($data);
}
and this is my model :
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('emp_id',$id);
$query = $this->db->get();
return $query->row();
}
public function book_update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
hey Eiji can you modify this code because, if I use this code I can do multiple update rows, but this code does not display modal bootstrap, it's just this code directly call the function in the controller, but have the same concept only this code can not display modal bootstrap, please
function update(id)
{
var list_id = [];
$("#id:checked").each(function() {
list_id.push(parseInt(this.value));
});
console.info(JSON.stringify(list_id));
if(list_id.length > 0)
{
if(confirm('Are you sure update this '+list_id.length+' data?'))
{
$.ajax({
type: 'POST',
data: {'devid_auto': list_id},
url: '<?php echo site_url('setting/mesin_update')?>',
success: function(result)
{
var hasil = result.replace(/\s/g,'');
if(hasil == 'y')
{
alert("Data Berhasil di Update");
location.reload();
}
else
{
alert('Failed.');
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error update data');
}
});
}
}
else
{
alert('no data selected');
}
}
Small correction in your html, Please delete the id="id", this is a big mistakes, because the id shoud be unique.
<input class="childbox" width="1%" type="checkbox" name="msg[]" align="center" value="" data-userid="<?php echo $d['emp_id'] ?>"/>
you have to define which of your line has been checked.
var user_id_list = []; //this will be the collection of id
//for each checked checkbox do...
$("input[type=checkbox].childbox").each(function(){
//get the user id value of the line
var the_userid = $(this).data('userid');
//add it to our collection
user_id_list.push( the_userid );
});
you find what is the option selected.
var new_dept = $("#modal_form select[name=dept_id_auto] option:selected").val();
You have to pass all this to your ajax request. So there is your ajax and a new function to add
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('proses/book_add')?>";
}
else
{
url = "<?php echo site_url('proses/book_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: prepareData(), //<-- here we call it
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
function prepareData(){
$data = [];
var user_id_list = []; //this will be the collection of id
//for each checked checkbox do...
$("input[type=checkbox].childbox").each(function(){
//get the user id value of the line
var the_userid = $(this).data('userid');
//add it to our collection
user_id_list.push( the_userid );
});
//select the new debt value
var new_dept = $("#modal_form select[name=dept_id_auto] option:selected").val();
//we pass all the data to an array
data.push('user_id_list',user_id_list);
data.push('new_dept', new_dept);
return data;
}
Now, in your controller, you should have two post data :
* new_dept, which content an int of the new dept
* user_id_list, which is an array of id.
So you just need to adapt your model and it's over.
Change the line
<div class="modal-footer">
<!-- change here -->
<button type="button" id="btnSave" onclick="prepareData()" class="btn btn-primary">Save</button>
<!-- end change -->
<button type="button" class="btn btn-info" data-dismiss="modal">Cancel</button>
</div>
Then, in your javascript function prepareData()
//we pass all the data to an array
data.push('user_id_list',user_id_list);
data.push('new_dept', new_dept);
//add this line for the debugging
alert( JSON.stringify(data) )
//this will display the current data value, even if it's an array/object or whatever
return data;
you can use my code for referenction
<td>
<button class="btn btn-success" data-toggle="modal" data-target="#r<?php echo $rule2->id_forward;?>">Edit </button>
<?=anchor('guru/hapus_rule/'.$rule2->id_forward,'Hapus',['class'=>'btn btn-danger btn-sm'])?>
</td>
<div class="modal modal-success" id="r<?php echo $rule2->id_forward;?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog">
<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" align="center">Edit Rule</h4>
</div>
<div class="modal-body">
<?php echo form_open_multipart('guru/ubah_rule/'.$rule2->id_forward);?>
<div class="form-group">
<label for="Kondisi">Kondisi 1</label>
<select class="form-control" name="kondisi">
<option value="">Pilih</option>
<?php foreach ($kondisi as $key) {?>
<option value="<?php echo $key->nama_kondisi?>" <?php if($rule2->gejala_1==$key->nama_kondisi){echo "selected";} ?>><?php echo $key->nama_kondisi; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="Kondisi_2">Kondisi 2</label>
<select class="form-control" name="kondisi_2">
<option value="">Pilih</option>
<?php foreach ($kondisi as $key) {?>
<option value="<?php echo $key->nama_kondisi?>" <?php if($rule2->gejala_2==$key->nama_kondisi){echo "selected";} ?>><?php echo $key->nama_kondisi; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="Kondisi_3">Kondisi 3</label>
<select class="form-control" name="kondisi_3">
<option value="">Pilih</option>
<?php foreach ($kondisi as $key) {?>
<option value="<?php echo $key->nama_kondisi?>" <?php if($rule2->gejala_3==$key->nama_kondisi){echo "selected";} ?>><?php echo $key->nama_kondisi; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="Kondisi_4">Kondisi 4</label>
<select class="form-control" name="kondisi_4">
<option value="">Pilih</option>
<?php foreach ($kondisi as $key) {?>
<option value="<?php echo $key->nama_kondisi?>" <?php if($rule2->gejala_4==$key->nama_kondisi){echo "selected";} ?>><?php echo $key->nama_kondisi; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="Kondisi_5">Kondisi 5</label>
<select class="form-control" name="kondisi_5">
<option value="">Pilih</option>
<?php foreach ($kondisi as $key) {?>
<option value="<?php echo $key->nama_kondisi?>" <?php if($rule2->gejala_5==$key->nama_kondisi){echo "selected";} ?>><?php echo $key->nama_kondisi; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="hasil">Hasil</label>
<input type="text" name="hasil" class="form-control" value="<?php echo $rule2->hasil; ?>">
</div>
<div class="form-group">
<label for="artikel">Artikel</label>
<select class="form-control" name="id_artikel">
<option value="">Pilih</option>
<?php foreach ($artikel as $data_rule) { ?>
<option value="<?php echo $data_rule->id_artikel; ?>" <?php if($rule2->id_artikel==$data_rule->id_artikel){echo "selected";} ?> ><?php echo $data_rule->judul; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="exampleInputFile">File Pembelajaran</label>
<input type="file" name="berkas" id="exampleInputFile">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-outline">Save changes</button>
</div>
</form>
</div>
<!-- /.modal-content -->
</div>
</div>

Failing to update certain records in the database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Well, for a good while I've now been stuck trying to figure out why most of my records are updating successfully while a certain few aren't. I've checked the php variable name/sql row names, ajax request and I don't see anything wrong. So here I am, hoping that someone can take a look at my code and help me figure out what's wrong.
Screenshot to show what I'm refering to.
Html/JS:
<div class="container">
<div class="page-header">
<h1>General Reservation
<small>Update, Delete</small>
</h1>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="container-fluid">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Name</th>
<th>Department/Group</th>
<th>On-site Contact</th>
<th>Phone</th>
<th>Email</th>
<th>Event Description</th>
<th>Setup Time</th>
<th>Number of Participants</th>
<th>Date</th>
<th>Start/End Time</th>
<th>Special Accommodations</th>
<th>Room</th>
<th>Room Style</th>
<th>Catering</th>
<th>Technical Equipment</th>
<th>Pre-Clean</th>
<th>On-clean</th>
<th>Post-Clean</th>
<th>Reserved Parkning</th>
<th>VIP</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/scripts.js"></script>
<script>
function viewGenData(){
$.ajax({
type: "GET",
url: "servergen.php",
success: function(data){
$('tbody').html(data);
}
});
}
function updateGenData(str){
var id = str;
var name = $('#name-'+str).val();
var dptGroup = $('#dptgroup-'+str).val();
var onSiteContact = $('#onsitecontact-'+str).val();
var phone = $('#phone-'+str).val();
var email = $('#email-'+str).val();
var eventDesc = $('#eventdesc-'+str).val();
var setUpTime = $('#setuptime-'+str).val();
var numOfParticipants = $('#partcnum-'+str).val();
var date = $('#date-'+str).val();
var startEndTime = $('#startendtime-'+str).val();
var specialAcc = $('#specialacc-'+str).val();
var room = $('#room-'+str).val();
var roomStyle = $('#roomstyle-'+str).val();
var catering = $('#catering-'+str).val();
var techEquip = $('#techequip-'+str).val();
var preClean = $('#preclean-'+str).val();
var postClean = $('#postclean-'+str).val();
var onClean = $('#onclean-'+str).val();
var rsvParking = $('#rsvparking-'+str).val();
var vip = $('#vip-'+str).val();
$.ajax({
type: "POST",
url: "servergen.php?p=edit",
data: "name=" + name + "&department=" + dptGroup + "&contact=" + onSiteContact + "&phone=" +
phone + "&email=" + email + "&description=" + eventDesc + "&setuptime=" + setUpTime + "&numberofparticipants=" + numOfParticipants +
"&date=" + date + "&startendtime=" + startEndTime + "&specialacc=" + specialAcc + "&room=" + room + "&roomstyle=" + roomStyle +
"&catering=" + catering + "&techequipment=" + techEquip + "&preclean=" + preClean + "&postclean=" + postClean + "&onclean=" + onClean +
"&rsvparking=" + rsvParking + "&vip=" + vip + "&id=" + id,
success: function(data){
viewGenData();
}
});
}
function deleteGenData(str){
var id = str;
$.ajax({
type: "GET",
url: "servergen.php?p=del",
data: "id="+id,
success: function(data){
viewGenData();
}
});
}
Php/mySQL:
<?php
include("db.php");
$page = isset($_GET['p'])?$_GET['p']:'';
if($page=='edit'){
$id = $_POST['id'];
$name = $_POST['name'];
$dptGroup = $_POST['dptgroup'];
$onSiteContact = $_POST['onsitecontact'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$eventDesc = $_POST['eventdesc'];
$setUpTime = $_POST['setuptime'];
$numOfParticipants = $_POST['partcnum'];
$date = $_POST['date'];
$startEndTime = $_POST['startendtime'];
$specialAcc = $_POST['specialacc'];
$room = $_POST['room'];
$roomStyle = $_POST['roomstyle'];
$catering = $_POST['catering'];
$techEquip = $_POST['techequip'];
$preClean = $_POST['preclean'];
$postClean = $_POST['postclean'];
$onClean = $_POST['onclean'];
$rsvParking = $_POST['rsvparking'];
$vip = $_POST['vip'];
$stmt = $db->prepare("update reservations set req_name=?, dept_group=?, onsite_contact=?, phone_num=?, email=?, event_description=?, setup_time=?, num_participants=?, date=?, start_end_time=?, notes=?, room=?, room_style=?, catering=?, tech_equip=?, pre_clean=?, post_clean=?, on_clean=?, reserved_parking=?, vip=? where id=?");
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$dptGroup);
$stmt->bindParam(3,$onSiteContact);
$stmt->bindParam(4,$phone);
$stmt->bindParam(5,$email);
$stmt->bindParam(6,$eventDesc);
$stmt->bindParam(7,$setUpTime);
$stmt->bindParam(8,$numOfParticipants);
$stmt->bindParam(9,$date);
$stmt->bindParam(10,$startEndTime);
$stmt->bindParam(11,$specialAcc);
$stmt->bindParam(12,$room);
$stmt->bindParam(13,$roomStyle);
$stmt->bindParam(14,$catering);
$stmt->bindParam(15,$techEquip);
$stmt->bindParam(16,$preClean);
$stmt->bindParam(17,$postClean);
$stmt->bindParam(18,$onClean);
$stmt->bindParam(19,$rsvParking);
$stmt->bindParam(20,$vip);
$stmt->bindParam(21,$id);
if($stmt->execute()){
echo "Success, data updated.";
} else{
echo "Failed, dated not updated.";
}
} else if($page=='del'){
$id = $_GET['id'];
$stmt = $db->prepare("delete from reservations where id=?");
$stmt->bindParam(1, $id);
if($stmt->execute()){
echo "Success, data deleted.";
} else{
echo "Failed to delete data.";
}
} else{
$stmt = $db->prepare("select * from reservations order by id desc");
$stmt->execute();
while($row = $stmt->fetch()){
?>
<tr>
<td><?php echo $row['req_name']?></td>
<td><?php echo $row['dept_group']?></td>
<td><?php echo $row['onsite_contact']?></td>
<td><?php echo $row['phone_num']?></td>
<td><?php echo $row['email'] ?></td>
<td><?php echo $row['event_description'] ?></td>
<td><?php echo $row['setup_time']?></td>
<td><?php echo $row['num_participants']?></td>
<td><?php echo $row['date']?></td>
<td><?php echo $row['start_end_time']?></td>
<td><?php echo $row['notes']?></td>
<td><?php echo $row['room']?></td>
<td><?php echo $row['room_style']?></td>
<td><?php echo $row['catering']?></td>
<td><?php echo $row['tech_equip']?></td>
<td><?php echo $row['pre_clean']?></td>
<td><?php echo $row['post_clean']?></td>
<td><?php echo $row['on_clean']?></td>
<td><?php echo $row['reserved_parking']?></td>
<td><?php echo $row['vip']?></td>
<td>
<button class="btn btn-warning" data-toggle="modal" data-target="#edit-<?php echo $row['id'] ?>">Update</button>
<!-- Modal -->
<div class="modal fade" id="edit-<?php echo $row['id'] ?>" tabindex="-1" role="dialog" aria-labelledby="editLabel-<?php echo $row['id'] ?>">
<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="editLabel-<?php echo $row['id'] ?>">Update Data</h4>
</div>
<form>
<div class="modal-body">
<input type="hidden" id="<?php echo $row['id'] ?>" value="<?php echo $row['id'] ?>">
<div class="form-group">
<label for="name-">Name of Requestor </label>
<input type="text" class="form-control" id="name-<?php echo $row['id'] ?>" value="<?php echo $row['req_name'] ?>" />
</div>
<div class="form-group">
<label for="phone-">Phone Number</label>
<input type="tel" class="form-control" id="phone-<?php echo $row['id'] ?>" value="<?php echo $row['phone_num'] ?>"" />
</div>
<div class="form-group">
<label for="setuptime-">Facilities/Catering Set-up time
</label>
<input type="text" class="form-control" id="setuptime-<?php echo $row['id'] ?>" value="<?php echo $row['setup_time'] ?>" />
</div>
<div class="form-group">
<label for="dptgroup-">Department/Group</label>
<input type="text" class="form-control" id="dptgroup-<?php echo $row['id'] ?>" value="<?php echo $row['dept_group'] ?>" />
</div>
<div class="form-group">
<label for="email-">Email Address</label>
<input type="email" class="form-control" id="email-<?php echo $row['id'] ?>" value="<?php echo $row['email'] ?>" />
</div>
<div class="form-group">
<label for="partcnum-">Number of Participants</label>
<input type="text" class="form-control" id="partcnum-<?php echo $row['id'] ?>" value="<?php echo $row['num_participants'] ?>" />
</div>
<div class="form-group">
<label for="onsitecontact-">On-site Contact</label>
<input type="text" class="form-control" id="onsitecontact-<?php echo $row['id'] ?>" value="<?php echo $row['onsite_contact'] ?>" />
</div>
<div class="form-group">
<label for="eventdesc-">Description of the Event</label>
<textarea id="eventdesc-<?php echo $row['id'] ?>" class="form-control" rows="5" cols="25" value="<?php echo $row['event_description'] ?>"><?php echo $row['event_description']?></textarea>
</div>
<div class="form-group">
<label for="date-">Date</label>
<input type="text" class="form-control" id="date-<?php echo $row['id'] ?>" value="<?php echo $row['date'] ?>" />
</div>
<div class="form-group">
<label for="startendtime-">Start/End Time (AM/PM)</label>
<input type="text" class="form-control" id="startendtime-<?php echo $row['id'] ?>" value="<?php echo $row['start_end_time'] ?>" />
</div>
<div class="form-group">
<label for="specialacc-">Special accommodations, notes or additional requirements</label>
<textarea id="specialacc-<?php echo $row['id'] ?>" class="form-control" rows="5" cols="25" value="<?php echo $row['notes'] ?>"><?php echo $row['notes']?></textarea>
</div>
<div class="form-group">
<label for="catering-">Is catering needed?</label>
<input type="text" class="form-control" id="catering-<?php echo $row['id'] ?>" value="<?php echo $row['catering'] ?>" />
</div>
<div class="form-group">
<label for="techequip-">Is technical equipment needed?</label>
<input type="text" class="form-control" id="techequip-<?php echo $row['id'] ?>" value="<?php echo $row['tech_equip'] ?>" />
</div>
<div class="form-group">
<label for="preclean-">Is pre-clean up needed?</label>
<input type="text" class="form-control" id="preclean-<?php echo $row['id'] ?>" value="<?php echo $row['pre_clean'] ?>" />
</div>
<div class="form-group">
<label for="onclean-">Is clean up during the event needed?</label>
<input type="text" class="form-control" id="onclean-<?php echo $row['id'] ?>" value="<?php echo $row['on_clean'] ?>" />
</div>
<div class="form-group">
<label for="postclean-">Is post clean up needed?</label>
<input type="text" class="form-control" id="postclean-<?php echo $row['id'] ?>" value="<?php echo $row['post_clean'] ?>" />
</div>
<div class="form-group">
<label for="rsvparking-">Is reserved parking needed?</label>
<input type="text" class="form-control" id="rsvparking-<?php echo $row['id'] ?>" value="<?php echo $row['reserved_parking'] ?>" />
</div>
<div class="form-group">
<label for="vip">Will there be a very important person will be in attendance (dignitaries, elected officials, high profile)?</label>
<input type="text" class="form-control" id="vip-<?php echo $row['id'] ?>" value="<?php echo $row['vip'] ?>" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" onclick="updateGenData(<?php echo $row['id'] ?>)" class="btn btn-primary">Update</button>
</div>
</form>
</div>
</div>
</div>
<button onclick="deleteGenData(<?php echo $row['id'] ?>)" class="btn btn-danger" style="width: 73.94px; margin-top: 2px">Delete</button>
</td>
</tr>
<?php
}
}
?>
First change ajax data section from:
data: "name=" + name + "&department=" + dptGroup + "&contact=" + onSiteContact + "&phone="
to:
data: {"name": name, department: dptGroup , [...]}
Second: You will always be doing the js code from the success section. If an error occurred, send the error status, eg:
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
And last: Show yourself error messages. It should define DEBUG constant and depending on the settings display more or less information about the error.

Form Validation before click the Create button; Modal body in Table

I have this problem to put a form validation in the modal form before dismiss-modal or before submitting the data.
In my modal-body I have no form-group instead put the input tags into table td.
So now I am wondering how can I put a form validation in this modal.
I have this html modal:
<div class="modal fade" id="myModalAdd" tabindex="-1" role="dialog" aria-labelledby="myModalLabelAdd" aria-hidden="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="false">
×
</button>
<h3 class="modal-title" id="myModalLabelAdd">Add User</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" id="search-form" role="form" method="post">
<table class="table table-bordered" id="edit_table">
<tbody>
<tr>
<td><b>First Name</b></td>
<td><input type="text" required class="typeahead form-control" id="first_name" placeholder="First Name" name="first_name"></td>
</tr>
<tr>
<td><b>Last Name</b></td>
<td><input type="text" required class="typeahead form-control" id="last_name" placeholder="Last Name" name="last_name"></td>
</tr>
<tr>
<td><b>Department</b></td>
<td><input type="text" required class="typeahead form-control" id="department" placeholder="Department" name="department"></td>
</tr>
<tr>
<td><b>Status</b></td>
<td>
<select required class="form-control" id="status">
<option value=""> </option>
<option value="Regular">Regular</option>
<option value="Probationary">Probationary </option>
<option value="Contractual">Contractual</option>
<option value="Trainee">Trainee</option>
</select>
</td>
</tr>
</tbody>
</table>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="close_add_button">
Close
</button>
<button type="button" class="btn btn-primary" data-dismiss="modal" id="create_employee"/>
Create
</button>
</div>
</div>
</div>
</div>
And I have this Jquery:
$(document).ready(function(
{
$( "#create_employee" ).click(function()
{
$.ajax({
url : '<?php echo base_url()?>employee/add_employee',
type: 'POST',
data: {
first_name: $('#first_name').val(),
last_name: $('#last_name').val(),
department: $('#department').val(),
status: $('#status').val()
},
success: function(msg){
var msg = $.parseJSON(msg);
employee_number = msg.EmployeeNo;
employee_first_name = msg.FirstName;
employee_last_name = msg.LastName;
$('#show_employee_number').append(employee_number);
$('#show_employee_first_name').append(employee_first_name);
$('#show_employee_last_name').append(employee_last_name);
$('#alert_success_show').modal('show');
}
});
});
});
Firstly, do not skip the server-side validation!
The following code is just checking for length but you could check for specific values etc.
$( function() {
$( '#search-form' ).on( 'submit', function(e) {
e.preventDefault();
var first = $( '#first_name' ).val();
var last = $( '#last_name' ).val();
if( first.length && last.length ) {
$( this ).submit();
} else {
alert( 'error' );
}
} );
} );
As of your edit:
$(document).ready(function(
{
$( "#create_employee" ).click(function()
{
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var department = $('#department').val();
var status = $('#status').val();
// Validate here
if( !first_name.length ) {
$( '#first_name' ).attr( 'style', 'border:1px solid red;' );
// The "right" way to do it would be
// $( '#first_name' ).addClass( 'error' );
// in css: .error{border:1px solid red;}
}
// etc etc
$.ajax({
url : '<?php echo base_url()?>employee/add_employee',
type: 'POST',
data: {
first_name: first_name,
last_name: last_name,
department: department,
status: status
},
success: function(msg){
var msg = $.parseJSON(msg);
employee_number = msg.EmployeeNo;
employee_first_name = msg.FirstName;
employee_last_name = msg.LastName;
// You are already using json so it would be simple to implement a error-handling-mechanism (pass {"status":"error"} or something equivalent.
$('#show_employee_number').append(employee_number);
$('#show_employee_first_name').append(employee_first_name);
$('#show_employee_last_name').append(employee_last_name);
$('#alert_success_show').modal('show');
}
});
});
});

Categories