How to multiple update rows with modal bottstrap - javascript

hello guys can you help me with my problem, i want to update multiple rows with modal bootstrap
So when I check the line and press the update button, it will appear modal bootstrap and I will update from there
I'm having trouble finding the script, can you help me finish my code?
this is the explanation
I checked the line
After that I press "Pindah Department" or in english "Move Departemen"
this basically updates quickly, just you check the line and press the "Move Departement" button, then bootstrap capital appears and you will select the value in the dropdown to update the line
this is my view :
<div class="row">
<div class="col-md-12">
<div class="panel panel-info">
<div class="panel-heading">Data Siswa Departemen ......</div>
<div class="panel-body">
<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="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[]" align="center" value="" data-userid="<?php echo $d['emp_id'] ?>"/>
</td>
<td width="1%" align="center"><?php echo $d['emp_id']; ?></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="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>
</div>
<div class="panel-footer">
<button class="btn btn-success" onclick="edit_book(<?php echo $d['emp_id'];?>)"> Move Departemen</button>
</div>
</div><!--end panel-->
<script src="<?php echo base_url() ?>assets/baru/jquery-3.2.1.min.js"></script>
<script src="<?php echo base_url() ?>assets/baru/jquery.dataTables.min.js"></script>
<script src="<?php echo base_url() ?>assets/baru/dataTables.bootstrap4.min.js"></script>
<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 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(),
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>
<!--modal-->
<div class="modal fade" id="modal_form" 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">Update Departemen</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 class="control-label col-md-3">Departemen</label>
<div class="col-md-9">
<select name="dept_id_auto" class="form-control pull-right">
<?php
foreach($groups as $c)
{
echo '<option value="'.$c['dept_id_auto'].'">'.$c['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>
</div><!-- end cols-->
</div><!--end row-->
I have trouble finding the script that will be called in the "Move Departement" button
This is my controller :
public function pindah_departemen()
{
// MASUKKAN PARAMETER DATA DISINI, BIASANYA HASIL DARI QUERY
$data = array(
'title' => 'Pindah Departemen',
'data' => $this->Pindah_dept_model->GetSiswa($this->input->get('filter_departemen'))
);
$data['groups'] = $this->Pindah_dept_model->getAllGroups();
$this->template->load('template','proses/pindah_departemen', $data);
}
public function book_update()
{
$data = array(
'dept_id_auto' => $this->input->post('dept_id_auto'),
);
$this->Pindah_dept_model->update_departemen(array('emp_id' => $this->input->post('emp_id')), $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);
}
This is my Model :
class Pindah_dept_model extends CI_Model
{
var $table = 'emp';
public function GetSiswa($dep=NULL)
{
$this->db->select(array('emp_id', 'first_name', 'nik', 'gender', 'pin', 'dept_name'))
->from('emp AS e')
->join('dept AS d','d.dept_id_auto = e.dept_id_auto', 'left');
if(!empty($dep)) $this->db->where('d.dept_id_auto', $dep);
$data = $this->db->order_by('emp_id','ASC')->get();
return $data->result_array();
}
public function getAllGroups()
{
$query = $this->db->query('SELECT dept_id_auto,dept_name FROM dept');
return $query->result_array();
}
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 update_departemen($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
please guys help me finish my code, i'm looking for a way out for my code for 2 weeks and still no results
Thanks Before

I don't know if I'm late or not.
You can try do something like below.
HTML
<label>Value 1 <input name='checkme[]' type='checkbox' value='1'></label><br>
<label>Value 2 <input name='checkme[]' type='checkbox' value='2'></label><br>
<label>Value 3 <input name='checkme[]' type='checkbox' value='3'></label><br>
<label>Value 4 <input name='checkme[]' type='checkbox' value='4'></label><br>
<br>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal_form" >Open Sesame</button>
<div class="modal fade" id="modal_form" 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">Update Departemen</h4>
</div>
<form action="#" id="form" class="form-horizontal">
<div class="modal-body form">
<input type="hidden" value="" name="emp_id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Departemen</label>
<div class="col-md-9">
<select name="dept_id_auto" class="form-control pull-right">
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">* This is supposed to be hidden value</label>
<div class="col-md-9">
<input name='list_check'>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="btnSave" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-info" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
Add hidden input, and we will get the checked value and store here later.
JAVASCRIPT
$(document).ready(function(){
$('#modal_form').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var recipient = button.data('whatever'); // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var vals = $('input:checkbox[name="checkme[]"]').map(function() {
return this.checked ? this.value : undefined;
}).get();
var modal = $(this);
modal.find('.modal-title').text("Open Sesame : Most code in here from bootstrap documentation. XD"); // just for fun.
modal.find(".modal-body input[name='list_check']").val(vals);
});
$("form").on("submit",function(x){
var val_submit = $(this).serialize(); // data to be send via ajax
alert("POST DATA : "+val_submit+"\n This is the value you will submit. The rest you can figure it out. Use explode() to split the list_check. And update like you want it.");
x.preventDefault();
});
});
After the button to open the modal. We will get the value from checkbox name checkme[]. This data need to be explode later in your php.
And try submit it.
I'm not going to take all your code. you need to figure out the rest by yourself. I just prepare example code that can be use. Maybe just like you want it. :)
JSFiddle Example : https://jsfiddle.net/synz/pyb7rjdo/

Related

how to post data from a php consult to a modal and generate a UPDATE

I am trying to pass data from an external query to a modal to be able to generate an update, but I notice that the variable of said query is not being passed to me, could you help me in what I am wrong, I am starting, my modal
<div id="content">
<button type="button" class="btn btn-danger" id= "hide" onclick="hide()">Close</button>
<form action="addcredits.php" method="POST" id="form1">
<input class="form-control" placeholder="Ingresa el total de efectivo" name="username" id="username">
<input type="button" name="btn" value="Ingresar" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" class="btn btn-default" />
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirmar
</div>
<div class="modal-body">
¿La cantidad ingresada es correcta?
<table class="table">
<tr>
<th>Efectivo</th>
<td id="uname"></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<input class="form-control" type="text" name="business_name" value="<?php echo $consult["id_students"]; ?>" placeholder="<?php echo $consul['id_students']; ?>">
<p><?php echo $consult["id_students"]; ?></p>
<p><?php echo $consult["id_students"]?></p>
Submit
</div>
</div>
</div>
</div>
</form>
and this is my extern consult
<?php
include("conection.php");
echo
'
<div class="container-fluid ">
<div class="row">
<div class="col-lg-12">
<table class="table table-hover">
<tr >
<th scope="col">Grupo</th>
<th scope="col">Nombre</th>
<th scope="col">Créditos</th>
</tr>
';
$accion = mysqli_real_escape_string($con,$_POST['accion']);
if($accion == 4)
{
$mi_busqueda = mysqli_real_escape_string($con,$_POST['mi_busqueda']);
$resultados = mysqli_query($con,"SELECT * FROM students WHERE
student_qr LIKE '%$mi_busqueda%'");
while($consult = mysqli_fetch_array($resultados))
{
echo
'
<tr >
<td>'.$consult["student_group"].'</td>
<td>'.$consult["student_name"]." " .$consult["student_secondname"]. " ". $consult["student_lastname"]. " ".'</td>
<td>'.$consult["student_credits"].'</td>
<td><button type="button" class="btn btn-warning" id= "show" onclick="show()" >Añadir Creditos</button></td>
</tr>
</div>
</div>
</div>
';
}
}
?>
I tried doing an echo but I don't see results, I suppose that the data remains from the external query, I don't know how I could generate said query on the same page by calling the modal instead of sending the data with javascript through JSON

Dynamic Loading of Data Via Ajax

I am new to AJAX and I am trying to load some data when clicked on a button to a modal, But the expected result is not being rendered and there are no errors thrown in the Developers Console.
The code AJAX code is as follows,
<script>
$(document).ready(function()
{
$(document).on('click','.edit_data', function(){
var employee_id = $(this).attr("User_ID");
$.ajax({
url:"fetchuser.php",
method:"POST",
data:{employee_id:employee_id},
dataType:"json",
success:function(data){
$('#floatingInputname').val(data.floatingInputname);
$('#add_data_Modal').modal('show');
}
});
});
});
</script>
And the fetchuser.php code is as follows,
<?php
include 'config.php';
if (isset($_POST['employee_id'])) {
$query = "SELECT * FROM gusers WHERE User_ID = '".$_POST['employee_id']."'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array($result);
echo json_encode($row);
}
?>
The HTML table structure where I have a button to be clicked for the modal with the data to load is as follows,
<table class="table" id="myTable" style="width: 100%;">
<thead>
<th scope="col">Image</th>
<th scope="col">Name</th>
<th scope="col">NIC</th>
<th scope="col">Contact</th>
<th scope="col">Role</th>
<th scope="col"></th>
</thead>
<tbody>
<?php
$queryguser = "SELECT * FROM `gusers`";
$gusersresult = mysqli_query($conn,$queryguser);
if ($gusersresult->num_rows>0) {
while ($gusersrow = mysqli_fetch_assoc($gusersresult)) {
?>
<tr>
<td scope="row">
<?php
if (empty($gusersrow['Image'])|| $gusersrow['Image']==null) {
?>
<img src="img/question (1).png" alt="No Profile" style="width:75px; height:75px; border-
radius:20px;">
<?php
}
else{
echo '<img src="data:image;base64,'.base64_encode($gusersrow['Image']).'" alt="Profile Image"
style="width:75px; height:75px; border-radius:50%;">';
}
?>
</td>
<td contenteditable="true" data-old_value="<?php $gusersrow['User_Name']; ?>"
onBlur="inlineedit(this,'User_Name','<?php echo $gusersrow["User_ID"]; ?>')"
onClick="highlightEdit(this);">
<?php echo $gusersrow["User_Name"]; ?>
</td>
<td contenteditable="true" data-old_value="<?php $gusersrow['User_NIC']; ?>"
onBlur="inlineedit(this,'User_NIC','<?php echo $gusersrow["User_ID"]; ?>')"
onClick="highlightEdit(this);">
<?php echo $gusersrow["User_NIC"]; ?>
</td>
<td contenteditable="true" data-old_value="<?php $gusersrow['User_Contact']; ?>"
onBlur="inlineedit(this,'User_Contact','<?php echo $gusersrow["User_ID"]; ?>')"
onClick="highlightEdit(this);">
<?php echo $gusersrow["User_Contact"]; ?>
</td>
<td contenteditable="true" data-old_value="<?php $gusersrow['Role']; ?>"
onBlur="inlineedit(this,'Role','<?php echo $gusersrow["User_ID"]; ?>')"
onClick="highlightEdit(this);">
<?php echo $gusersrow["Role"]; ?>
</td>
<td scope="row" class="text-center"><input type="button" name="edit" value="Edit" id="<?php echo
$gusersrow["User_ID"]; ?>" class="btn btn-info btn-xs edit_data" /></td>
</tr>
<?php
}
}else{
echo "No Records Found";
}
?>
</tbody>
</table>
And the Modal i want the data to be displayed
<div class="modal fade" id="exampleModaluserupdate" tabindex="-1" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Update User Data</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form action="" method="post">
<div class="row" style="width:100%;">
<div class="col-md-6">
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputname">
<label for="floatingInputname">Name</label>
</div>
</div>
<div class="col-md-6">
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInputnic">
<label for="floatingInputnic">NIC</label>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Further to this i have the following JS scripts loaded in my <head> tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

Bootstrap modal does not showing information

I have entered an internship for 6 month and I'm currently developing a web system using Bootstrap modal. I am experiencing an issue where my modal view is failing to show any information. There are no errors in the scripting but I do not know how to fix it. Its just blank. Any suggestion?
This is modal view for staff detail which is showing no information:
Below is the code from the two of files that are being used to show the modal view.
index.html
<?php
//index.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM tbl_user ORDER BY user_id DESC";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>ADD NEW USER</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:700px;">
<h3 align="center">Admin Log Site </h3>
<br />
<div class="table-responsive">
<div align="right">
<button type="button" name="age" id="age" data-toggle="modal" data-target="#add_data_Modal" class="btn btn-warning">Add New User</button>
</div>
<br />
<div id="employee_table">
<table class="table table-bordered">
<tr>
<th width="70%">Staff Name</th>
<th width="30%">View</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["uname"]; ?></td>
<td><input type="button" name="view" value="view" id="<?php echo $row["user_id"]; ?>" class="btn btn-info btn-xs view_data" /></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</div>
</body>
</html>
<!-- modal insert division -->
<div id="add_data_Modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">ADMIN SITE</h4>
</div>
<div class="modal-body">
<form method="post" id="insert_form">
<label>Enter Staff Username</label>
<input type="text" name="uname" id="uname" class="form-control" />
<br />
<label>Enter Staff ID</label>
<input type="text" name="staff_number" id="staff_number" class="form-control" />
<br />
<label>Staff Roles</label>
<select name="staff_role" id="staff_role" class="form-control">
<option value="Administration">Administration</option>
<option value="Project Manager">Project Manager</option>
<option value="Staff">Staff</option>
</select>
<br />
<label>Password</label>
<input type="text" name="password" id="password" class="form-control" />
<br />
<input type="submit" name="insert" id="insert" value="Add user" class="btn btn-success" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- modal view employer -->
<div id="dataModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Staff Details</h4>
</div>
<div class="modal-body" id="employee_detail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$('#insert_form').on("submit", function(event){
event.preventDefault();
if($('#uname').val() == "")
{
alert("Name is required");
}
else if($('#staff_number').val() == "")
{
alert("Staff id is required");
}
else if($('#staff_role').val() == "")
{
alert("Staff role is required");
}
else if($('#password').val() == "")
{
alert("password is required");
}
else
{
$.ajax({
url:"insertdata.php",
method:"POST",
data:$('#insert_form').serialize(),
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#employee_table').html(data);
}
});
}
});
$(document).on('click', '.view_data', function(){
//$('#dataModal').modal();
var user_id = $(this).attr("user_id");
$.ajax({
url:"view.php",
method:"POST",
data:{user_id:user_id},
success:function(data){
$('#employee_detail').html(data);
$('#dataModal').modal('show');
}
});
});
});
</script>
For the view inforamtion as follow.
view.php
<?php
//select.php
if(isset($_POST["user_id"]))
{
$output = '';
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM tbl_user WHERE user_id = '".$_POST["user_id"]."'";
//$query = "SELECT * FROM tbl_user WHERE user_id = '".$_POST["id"]."'";
$result = mysqli_query($connect, $query);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td width="30%"><label> Staff Name</label></td>
<td width="70%">'.$row["uname"].'</td>
</tr>
<tr>
<td width="30%"><label>Staff Id</label></td>
<td width="70%">'.$row["staff_number"].'</td>
</tr>
<tr>
<td width="30%"><label>Staff Role</label></td>
<td width="70%">'.$row["staff_role"].'</td>
</tr>
<tr>
<td width="30%"><label>password</label></td>
<td width="70%">'.$row["password"].'</td>
</tr>
';
}
$output .= '</table></div>';
echo $output;
}
?>
Your problem is that your $.ajax POST is sending JSON data but your PHP view is looking for items in $_POST.
To set $_POST values try this:
$.ajax({
url: "view.php",
method: "POST",
data: "user_id="+user_id,
success: function(data) {
$('#employee_detail').html(data);
$('#dataModal').modal('show');
}
});
Note: Typically your input elements would be inside of a <form> tag. When they are you can use $('#formid').serialize() to convert your input elements into a string that you can pass to the ajax call as the data variable.
For example:
<form id="getUserDetails">
<label for="user_id">A bar</label>
<input id="user_id" name="user_id" type="text" value="" />
<input type="submit" value="Send" onclick="PostThis();return false;
/>
</form>
var data = $('#getUserDetails').serialize();
$.ajax({
url: "test.php",
type: "post",
data: data ,
success: function (response) {
$('#employee_detail').html(response);
$('#dataModal').modal('show');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});

Bootstrap Modal Submit form

I've been searching all over and trying different combinations. I will try to explain exactly what I need. I have a table populated with SQL data, last column is an Edit button to open a bootstrap modal. I've been able to populate the table and create the edit button to pass the row id into the modal for the query on the modal populate all inputs with actual data on DB. Everything is working. But now I can't even make a POST on the form, I hit the button and nothing happens.
<?php
require 'style/header.php';
require 'core/db_connect.php';
?><div class="main">
<div class="row">
<table class= "table table-striped table-bordered table-hover">
<thead>
<tr>
<th colspan="1" rowspan="1" style="width: 180px;" tabindex="0">BI/CC</th>
<th colspan="1" rowspan="1" style="width: 220px;" tabindex="0">Name</th>
<th colspan="1" rowspan="1" style="width: 288px;" tabindex="0">Supplier Number</th>
<th colspan="1" rowspan="1" style="width: 40px;" tabindex="0">Actions</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT bicc, name, supplier_number ";
$query .= "FROM ext_work_risk ";
$result = sqlsrv_query($dbhandle, $query);
$i=0;
while($fetch = sqlsrv_fetch_array($result))
{
if($i%2==0) $class = 'even'; else $class = 'odd';
echo'<tr class="'.$class.'">
<td>'.$fetch['bicc'].'</td>
<td>'.$fetch['name'].'</td>
<td>'.$fetch['supplier_number'].'</td> <td><a class="modalButton" data-bicc="'.$fetch['bicc'].'"><button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#modal_edit" data-container="body">Edit</button></a></td>
</tr>';
}
?>
</tbody>
</table>
</div>
</div>
<div id="modal_edit" class="modal fade" style="font-weight: normal;">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
<?php require 'style/footer.php' ?>
<!-- Script Part -->
<script type="text/javascript">
$('.modalButton').click(function(){
var bicc = $(this).attr('data-bicc');
$.ajax({url:"modal/ajax_ext_risk_modal_edit.php?bicc="+bicc,cache:false,success:function(result){
$(".modal-content").html(result);
}});
});
</script>
Now the "modal/ajax_ext_risk_modal_edit.php" file:
<?php
$bicc = $_GET['bicc'];
//DB connect settins
require '../core/db_connect.php';
$query = "SELECT * ";
$query .= "FROM ext_work_risk WHERE bicc='$bicc'";
$result = sqlsrv_query($dbhandle, $query);
$fetch = sqlsrv_fetch_array($result);
?>
<!-- Modal -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit Co-Worker</h4>
</div>
<div class="modal-body">
<p>To edit just type the new date in the format <b>YYYY/MM/DD</b> and click save.
<form class="form-horizontal" role="form" method="POST" action="../core/process_ext_risk_modal.php">
<div class="form-group">
<label class="control-label col-sm-4">BI/CC:</label>
<div class="col-sm-7">
<input class="form-control" id="bicc" name="bicc" readonly="readonly" value="<?php echo $fetch['bicc']; ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4">Name:</label>
<div class="col-sm-7">
<input class="form-control" id="name" readonly="readonly" value="<?php echo $fetch['name']; ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4">Sup. Number:</label>
<div class="col-sm-7">
<input class="form-control" id="supplier_number" readonly="readonly" value="<?php echo $fetch['supplier_number']; ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4">LOTO:</label>
<div class="col-sm-7">
<input class="form-control" id="loto" name="loto" <?php $loto = $fetch['loto']->format('Y/m/d'); if ($loto == "2000/01/01") {echo "placeholder='Please insert date'";} else {echo "value='$loto'";} ?>>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4">Lift Platform:</label>
<div class="col-sm-7">
<input class="form-control" id="lift_platform" <?php $lift_platform = $fetch['lift_platform']->format('Y/m/d'); if ($lift_platform == "2000/01/01") {echo "placeholder='Please insert date'";} else {echo "value='$lift_platform'";} ?>>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-default btn-success" type="submit" name="submit" value="Submit">Save</button>
</div>
When I hit Save button nothing happens. Here is the ../core/process_ext_risk_modal.php file:
<?php
include("db_connect.php");
if(isset($_POST["save"])) {
$id = $_POST['bicc'];
$data = $_POST['loto'];
if(sqlsrv_query($dbhandle, "update ext_work_risk set loto='$data' where bicc='$id'"))
echo 'success';
}
?>
This last file is just for testing of course I will be Updating much more data on the form submit.
Thank you
I just found the problem thanks to Fred -ii tips:
So here is the previous code block:
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-default btn-success" type="submit" name="submit" value="Submit">Save</button>
</div>
And now the corrected one:
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button class="btn btn-default btn-success" type="submit" name="submit" value="Submit">Save</button>
</div>
</form>
Also changing if(isset($_POST["save"])) to if(isset($_POST["submit"])). Main problem being having submit outside form and two types defined on the same button.

Creating a CRUD using PHP + Bootstrap Modal + Mysql + JS [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need a page with a button to insert a new user, with fields "country","name" and "company". Then, in the same page, I need to list those datas and in front each item it'll appear two buttons, "edit" and "delete". At edit button, I need to display a Modal window (bootstrap), so I could update this data.
I hope someone could help me.
Thanks
Sorry, I've forgot to paste the code.
This is my index.php:
<form action="inserir.php" method="post" name="visitas" id="visitas">
<table class="table_geral" align="center" width="350" border="0" cellspacing="0" cellpadding="3">
<tr>
<td width="200">Pais:</td>
<td>
<?
$array_pais = array('Selecione...','Alemanha','Angola','Argentina','Bolívia','Brasil','Camarões','Canadá','Chile','China','Colombia',
'Costa Rica','Cuba','Dinamarca','Equador','Espanha','Estados Unidos','França','Holanda','Inglaterra','Itália','Japão',
'México','Nigéria','Panamá','Paraguai','Peru','Porto Rico','Portugal','Rússia','Senegal','Taiwan','Uruguai','Venezuela'
);
echo '<select class="form-control" style="width:330px" name="pais" id="pais">';
foreach($array_pais as $valor){
echo '<option>'.$valor.'</option>';
}
echo '</select>';
?>
</td>
<td height="29" valign="center" align="center" rowspan="3">&nbsp </td>
<td height="29" valign="center" align="center" rowspan="3">
<input type="submit" name="Submit" class="btn btn-success btn-lg" value=" + ">
</td>
</tr>
<tr>
<td width="411">Nome:</td>
<td width="339">
<input class="form-control" name="nome" type="text" id="nome" size="50">
</td>
</tr>
<tr>
<td width="411">Empresa:</td>
<td width="339">
<input class="form-control" name="empresa" type="text" id="empresa" size="50" style="text-transform:uppercase;">
</td>
</tr>
</table>
</form>
$sql = "SELECT * FROM tb_visitas ORDER BY empresa";
$limite = mysql_query("$sql"); ?>
<table data-toggle="table" data-cache="false">
<thead align="center">
<tr height="35px" valign="center" bgcolor="#B0E2FF" >
<th style="text-align:center; vertical-align:middle; width="100px">PAÍS</th>
<th style="text-align:center; vertical-align:middle; width="250px">NOME</th>
<th style="text-align:center; vertical-align:middle; width="300px">EMPRESA</th>
<th style="text-align:center; vertical-align:middle; width="5px" colspan="2">AÇÕES</th>
</tr>
</thead>
<? while($result = mysql_fetch_array($limite)){ ?>
<tbody>
<tr>
<td style="display:none" align="center"><?=$result['id']; $_SESSION=$result['id'];?></td>
<td style="vertical-align:middle;"> <?=$result['pais']?></td>
<td style="vertical-align:middle;"> <?=$result['nome']?></td>
<td style="text-transform:uppercase; vertical-align:middle;"><?=$result['empresa']?></td>
<td style="width:20px">
<form action="editar.php" method="post">
<a class="btn btn-primary glyphicon glyphicon-pencil" title="Editar" href="editar.php?id=<?=$result['id'];?>"></a>
</form>
</td>
<td style="width:20px">
<a class="btn btn-danger glyphicon glyphicon-trash" title="Deletar" href="deletar.php?id=<?=$result['id'];?>"></a>
</td>
</tr>
</tbody>
<?}?>
</table>
<div class="container">
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">
<span class="glyphicon glyphicon-pencil"></span> Novo registro</h4>
</div>
<div class="modal-body">
<p></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
</div>
</div>
</div>
</div>
</div>
<script>
$('form').submit(function () {
var postdata = {
pais: $(this)[0].pais.value,
nome: $(this)[0].nome.value,
empresa: $(this)[0].empresa.value
}
$.post("inserir.php", postdata, function (d) {
$('#myModal').find(".modal-body").html(d);
$('#myModal').modal('show');
});
return false;
});
</script>
And it's my inserir.php:
<?
require("conexao.php");
$pais = $_POST['pais'];
$nome = $_POST['nome'];
$empresa = $_POST['empresa'];
if (($pais == "") || ($pais == "Selecione...") || ($nome == "") || ($empresa == "")) {
echo "Favor preencha todos os campos!";
} else {
$sql = mysql_query("SELECT nome FROM tb_visitas WHERE nome='$nome'");
if (mysql_num_rows($sql) > 0) {
echo "O nome <b>$nome</b> ja foi inserido na lista!";
} else {
$sqlinsert = "INSERT INTO tb_visitas VALUES (null, '$pais', '$nome', UPPER('$empresa'))";
mysql_query($sqlinsert) or die (mysql_error());
echo "Gravado com sucesso!";
}
}
?>
With assist from CodeGodie now I have this code, but I need to open a Modal window (bootstrap) to edit some register. However I don't know how to make it with AJAX. I feel sorry for my bad explanation and my English. Thanks
Sorry, but I'm beginner in php and ajax. There are much code that I've never seen :( ....Then, I'm having some difficulty to make it work out. I thought it was simplest. However I tried to make the files:
editar.php
$con = mysql_connect("localhost", "root", "", "visitas");
// Check connection
if (mysql_error()) {
echo "Failed to connect to MySQL: " . mysql_error();
}
$id = $_POST['id'];
$nome = $_POST['nome'];
$empresa = $_POST['empresa'];
$pais = $_POST['pais'];
$query = "UPDATE tb_visitas SET nome = '$nome', empresa = '$empresa', pais= '$pais' WHERE id = $id ";
if (mysql_query($con, $query)) {
$res['response'] = true;
$res['message'] = "Record has been updated";
} else {
$res['response'] = false;
$res['message'] = "Error: " . $query . "<br>" . mysql_error($con);
}
echo json_encode($res);
deletar.php
<?php
require("conexao.php");
$id = $_POST['id'];
if (isset($_POST['id'])) {
$sql = "DELETE FROM tb_visitas WHERE id = $id";
$deletar = mysql_query($sql) or die (mysql_error());
}
?>
get_list.php
$con = mysql_connect("localhost", "root", "", "visitas");
if (mysql_error()) {
echo "Failed to connect to MySQL: " . mysql_error();
}
$id = $_POST['id'];
$nome = $_POST['nome'];
$empresa = $_POST['empresa'];
$pais = $_POST['pais'];
$query = "SELECT * FROM tb_visitas";
?>
conexão.php
<?
error_reporting(E_ALL ^ E_DEPRECATED);
$hostname = 'localhost';
$username = 'root';
$senha = '';
$banco = 'visitas';
$db = mysql_connect($hostname, $username, $senha);
mysql_set_charset('latin1',$db);
mysql_select_db($banco, $db) or die ("Não foi possível conectar ao banco MySQL");
?>
I see what you have now. Thanks for adding the code. I would first focus on design. It sounds like you want some sort of CRUD(Create Retrieve Update Delete) system. In that case, what I would do, is place the initial submission form on top (like what you have), and use modals to show any alert messages and the Edit form.
The design would look like this:
+-------------------------------------+
| Submit Form |
| - input |
| - input |
+-------------------------------------+
| List showing DB info |
| - result 1 (with Edit/Delete links) |
| - result 2 (with Edit/Delete links) |
| ... |
+-------------------------------------+
At page load, you will run an JS function, we can call it update_list(), that will use AJAX to fetch all the database info and parse it in the List container.
Then you will delegate Edit/Delete Click events to call the desired AJAX calls.
Keep in mind, this design structure separates everything in functions and uses AJAX to call on PHP scripts. The data will be sent via JSON.
Now, when you Submit the submission form, this will also use AJAX to send POST requests to PHP, then once submitted, JS will use Bootstrap's modal to show messages.
When the edit link is clicked, JS will again open a Bootstrap modal to show the edit form.
With that said, this is how I would do it :
<html>
<title>Modal</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<style>
#wrapper {
padding: 10px;
}
.modal-header, h4, .close {
background-color: #5cb85c;
color: white !important;
text-align: center;
font-size: 30px;
}
.modal-footer {
background-color: #f9f9f9;
}
</style>
</head>
<body>
<div id="wrapper">
<form id="submit_form" role="form" style="width: 300px;">
<div class="form-group">
<label for="pais">Pais:</label>
<?php
$array_pais = array('Selecione...', 'Alemanha', 'Angola', 'Argentina', 'Bolívia', 'Brasil', 'Camarões', 'Canadá', 'Chile', 'China', 'Colombia',
'Costa Rica', 'Cuba', 'Dinamarca', 'Equador', 'Espanha', 'Estados Unidos', 'França', 'Holanda', 'Inglaterra', 'Itália', 'Japão',
'México', 'Nigéria', 'Panamá', 'Paraguai', 'Peru', 'Porto Rico', 'Portugal', 'Rússia', 'Senegal', 'Taiwan', 'Uruguai', 'Venezuela'
);
echo '<select class="form-control" name="pais" id="pais">';
foreach ($array_pais as $valor) {
echo '<option>' . $valor . '</option>';
}
echo '</select>';
?>
</div>
<div class="form-group">
<label for="nome">Nome:</label>
<input class="form-control" name="nome" type="text" id="nome" size="50">
</div>
<div class="form-group">
<label for="empresa">Empresa:</label>
<input class="form-control" name="empresa" type="text" id="empresa" size="50" style="text-transform:uppercase;">
</div>
<input type="submit" name="Submit" class="btn btn-success btn-lg" value="+">
</form>
<table id="list" class="table">
<thead align="center">
<tr bgcolor="#B0E2FF">
<th>PAÍS</th>
<th>NOME</th>
<th>EMPRESA</th>
<th>AÇÕES</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="modals_container">
<div class="modal fade" id="message_modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Message</h4>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="edit_modal" role="dialog">
<div class="modal-dialog">
<form id="edit_form" class="form">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit</h4>
</div>
<div class="modal-body">
<div class="form-group">
Country: <input id="country_input" type="text" name="country">
</div>
<div class="form-group">
Nome: <input id="username_input" type="text" name="username">
</div>
<div class="form-group">
Company: <input id="company_input" type="text" name="company">
</div>
<input id="id_input" type="hidden" name="id">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default">submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
function update_list() {
$.getJSON("get_list.php", function (data) {
if (data.response) {
$("#list").find("tbody").empty();
data.results.forEach(function (i) {
console.log(i);
$("#list").find("tbody").append(
"<tr>" +
"<td>" + i.country + "</td>" +
"<td>" + i.username + "</td>" +
"<td>" + i.company + "</td>" +
"<td><a class='edit_link' href='" + JSON.stringify(i) + "'>edit</a> | <a class='delete_link' href='" + i.id + "'>delete</a></td>" +
"</tr>"
);
});
}
});
}
update_list();
$('#submit_form').submit(function () {
$.ajax({
url: "main.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
if (data.response) {
var $modal = $('#message_modal');
$modal.find(".modal-body").html(data.message);
$modal.modal('show');
update_list();
} else {
alert(data.message);
}
}
});
return false;
});
$("#list").delegate('.edit_link', 'click', function (e) {
e.preventDefault();
var info = JSON.parse($(this).attr("href"));
var $modal = $("#edit_modal");
$modal.find("#country_input").val(info.country);
$modal.find("#company_input").val(info.company);
$modal.find("#username_input").val(info.username);
$modal.find("#id_input").val(info.id);
$modal.modal('show');
});
$('#edit_form').submit(function () {
$.ajax({
url: "edit.php",
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
if (data.response) {
var $modal = $('#message_modal');
$("#edit_modal").modal('hide');
$modal.find(".modal-body").html(data.message);
$modal.modal('show');
update_list();
} else {
alert(data.message);
}
}
});
return false;
});
</script>
</body>
</html>
edit.php should be something like this:
$con = mysqli_connect("localhost", "root", "", "test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST['id'];
$nome = $_POST['username'];
$company = $_POST['company'];
$country = $_POST['country'];
$query = "UPDATE table SET username = '$nome', company = '$company', country= '$country' WHERE id = $id ";
if (mysqli_query($con, $query)) {
$res['response'] = true;
$res['message'] = "Record has been updated";
} else {
$res['response'] = false;
$res['message'] = "Error: " . $query . "<br>" . mysqli_error($con);
}
echo json_encode($res);
Try this out, and let me know what you think.
I've not changed much php code of yours. I added little code to it.
In , i added code to call editar.php modal. In that script tag.. more code were there.. I don't know what is that.
index.php
//
Your original code here(No changes). From down, it started changing
//
<table data-toggle="table" data-cache="false">
<thead align="center">
<tr height="35px" valign="center" bgcolor="#B0E2FF" >
<th style="text-align:center; vertical-align:middle; width="100px">PAÍS</th>
<th style="text-align:center; vertical-align:middle; width="250px">NOME</th>
<th style="text-align:center; vertical-align:middle; width="300px">EMPRESA</th>
<th style="text-align:center; vertical-align:middle; width="5px" colspan="2">AÇÕES</th>
</tr>
</thead>
<? while($result = mysql_fetch_array($limite)){ ?>
<tbody>
<tr>
<td style="display:none" align="center"><?=$result['id']; $_SESSION=$result['id'];?></td>
<td style="vertical-align:middle;"> <?=$result['pais']?></td>
<td style="vertical-align:middle;"> <?=$result['nome']?></td>
<td style="text-transform:uppercase; vertical-align:middle;"><?=$result['empresa']?></td>
<td style="width:20px">
//Some Changes Here.. check it
<a class='btnEdit' href="#form_modal" data-toggle="modal" data-EditID="<?echo $result['id'];?>">
<span class='glyphicon glyphicon-pencil'></span>
<a>
</td>
<td style="width:20px">
<a class="btn btn-danger glyphicon glyphicon-trash" title="Deletar" href="deletar.php?id=<?=$result['id'];?>"></a>
</td>
</tr>
</tbody>
<?}?>
</table>
//Add this code.
<div id="form_modal" class="modal fade" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
//Added few codes in script for calling modal.
<script>
$('form').submit(function () {
var postdata = {
pais: $(this)[0].pais.value,
nome: $(this)[0].nome.value,
empresa: $(this)[0].empresa.value
}
$.post("inserir.php", postdata, function (d) {
$('#myModal').find(".modal-body").html(d);
$('#myModal').modal('show');
});
return false;
});
$('.btnEdit').click(function(){
var id=$(this).attr('data-EditID');
$.ajax({url:"editar.php?id="+id,cache:false,success:function(result){
$(".modal-content").html(result);
}});
});
</script>
Make One editar.php. Paste this below code in that page.
editar.php
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">
<span class="glyphicon glyphicon-pencil"></span> Novo registro
</h4>
</div>
<div class="modal-body" style='text-align:justify;'>
<?echo $_GET['id'];?>
//Show Details Here.
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
</div>

Categories

Resources