I was trying to implement this guide from this page: How to update an HTML table content without refreshing the page?
I somehow managed to implement it, unfortunately the Client-Side dataTable is destroyed when refreshing it.
By destroyed, all the data in the dataTable is in a single page.
This is the table.
<table id="earnings_amendment_account" class="table table-bordered" style="table-layout: fixed; display: none">
<thead>
<th></th>
<th>Account Code</th>
<th>Account Title</th>
<th>Account Type</th>
<th>Tools</th>
</thead>
<tbody id="table-body">
<?php include 'tableBody.php';?>
</tbody>
</table>
This is the tableBody.php
<?php include 'backend/conn.php'; ?>
<?php
$params=array();
$sql = "SELECT accountcode,accounttype,accounttitle,accounttype,postedby,dateposted,approvedby,dateapproved FROM earningsamendmentaccount";
$query = sqlsrv_query($conn, $sql, $params, array("Scrollable" => SQLSRV_CURSOR_KEYSET));
if ($query === false ) { echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true); exit; }
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
echo "
<tr data-key-1='".$row['postedby']."' data-key-2='".$row['dateposted']."' data-key-3='".$row['approvedby']."' data-key-4='".$row['dateapproved']."'>
<td class='details-control'></td>
<td>".$row['accountcode']."</td>
<td>".$row['accounttitle']."</td>
<td>".$row['accounttype']."</td>
<td>
<button class='btn btn-default btn-sm view btn-flat' data-id='".$row['accountcode']."'><i class='fa fa-eye'></i> View</button>
<button class='btn btn-success btn-sm edit btn-flat' data-id='".$row['accountcode']."'><i class='fa fa-edit'></i> Edit</button>
<button class='btn btn-danger btn-sm delete btn-flat' data-id='".$row['accountcode']."'><i class='fa fa-trash'></i> Delete</button>
" ?>
<?php if (empty($row['approvedby'])) { echo " <button class='btn btn-warning btn-sm approve btn-flat' data-id='".$row['accountcode']."'><i class='fa fa-check-square-o'></i> Approve</button> "; } ?>
<?php "
</tr>
";
}
?>
This is my jQuery/AJAX - (earnings_amendment_account.php)
function SubmitFormData() {
var add = $("#add").val();
var add_accountcode = $("#add_accountcode").val();
var accounttitle = $("#accounttitle").val();
var accounttype = $("#accounttype").val();
var postedby = $("#postedby").val();
var dateposted = $("#dateposted").val();
$.post("earnings_amendment_account_add.php",
{
add: add,
add_accountcode: add_accountcode,
accounttitle: accounttitle,
accounttype: accounttype,
postedby: postedby,
dateposted: dateposted
},
function(data) {
$('#results').html(data);
$('#myForm')[0].reset();
$.get("tableBody.php", function(data) {
$("#table-body").html(data);
$("#earnings_amendment_account").DataTable().ajax.reload();
});
});
}
This is the modal being called.
<form autocomplete='off' id="myForm" class="form-horizontal" method="POST" action="earnings_amendment_account_add.php">
<!-- Table Loader -->
<div class="form-group" id="earnings_amendment_account_modalload">
<div class="col-sm-9" id= "earnings_amendment_account_modalload" style="width:100%">
</div></div>
<div class="form-group">
<label for="accounttitle" class="col-sm-3 control-label">Account Title</label>
<div class="col-sm-9">
<input type="text" autocomplete="off" class="form-control" id="accounttitle" name="accounttitle" style="text-transform:uppercase;width:90%" required>
</div>
</div>
<div class="form-group" hidden>
<label for="postedby" class="col-sm-3 control-label">Posted By</label>
<div class="col-sm-9">
<input type="text" autocomplete="off" class="form-control" id="postedby" name="postedby" value="<?php echo $user['firstname'].' '.$user['lastname']; ?>" required>
</div>
</div>
<div class="form-group" hidden>
<label for="dateposted" class="col-sm-3 control-label">Posted By</label>
<div class="col-sm-9">
<input type="text" autocomplete="off" class="form-control" id="dateposted" name="dateposted" value="<?php echo gmdate('Y-m-d h:i:s'); ?>" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default info btn-flat pull-left" data-dismiss="modal"><i class="fa fa-close"></i> Close</button>
<button type="button" onclick="SubmitFormData();" class="btn btn-primary btn-flat" name="add"><i class="fa fa-save"></i> Save</button>
<div id="results"></div>
</form>
This is the dataTable.
function format ( dataSource ) {
var html = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;" class="table table-bordered">';
for (var key in dataSource){
html += '<tr>'+
'<td>' + key +'</td>'+
'<td>' + dataSource[key] +'</td>'+
'</tr>';
} return html += '</table>'; }
var earnings_amendment_account_table = $('#earnings_amendment_account').DataTable({});
// Add event listener for opening and closing details
$('#earnings_amendment_account').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = earnings_amendment_account_table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format({
'Posted By : ' : tr.data('key-1'),
'Date Posted : ' : tr.data('key-2'),
'Approved By : ' : tr.data('key-3'),
'Date Approved : ' : tr.data('key-4')
})).show();
tr.addClass('shown');
} });
Is there a way for this to be fixed?
try use your datatable object
var earnings_amendment_account_table = $('#earnings_amendment_account').DataTable({});
so on your jQuery/AJAX - (earnings_amendment_account.php) change $("#earnings_amendment_account").DataTable().ajax.reload(); to earnings_amendment_account_table.ajax.reload();
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/
I have this AJAX code that will insert data to my CRUD table. But when I click the button that will save/insert the data to my table it will not show. All I want here is to insert my data using AJAX to my table without refreshing or using the form element in html.
Here is my code with my modal and the body of my table:
$(document).ready(function() {
// Add
$('#btn_add').click(function() {
var id = $('#brand_id').val();
var bname = $('#bname').val();
var bstatus = $('#bstatus').val();
$.ajax({
url: 'add_brand.php',
method: 'POST',
data: {
bname: bname,
bstatus: bstatus
},
success: function(data) {
$('#' + id).children('td[data-target=brand_name]').text(bname);
$('#' + id).children('td[data-target=brand_status]').text(bstatus);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal fade" id="modal-default">
<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">Add a brand</h4>
</div>
<div class="modal-body">
<input type="hidden" id="brand_id" />
<div class="form-group">
<label for="bname">Brand Name</label>
<input type="text" class="form-control" id="bname" name="bname" placeholder="Brand Name" />
</div>
<div class="form-group">
<label for="bstatus">Status</label>
<select class="form-control select2" style="width: 100%;" id="bstatus" name="bstatus">
<option>Available</option>
<option>Not Available</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" id="btn_add">Save Changes</button>
</div>
</div>
</div>
</div>
<tbody>
<?php
include("db_connect/connect.php");
$query = mysqli_query($con, "SELECT * FROM brand");
while ($row = mysqli_fetch_array($query)) { ?>
<tr id="<?php echo $row['brand_id']; ?>">
<td data-target="brand_name"><?php echo $row["brand_name"]; ?></td>
<td data-target="brand_status"><?php echo $row["brand_status"]; ?></td>
<td>
<a data-role="edit" data-id="<?php echo $row['brand_id']; ?>" class="btn btn-success"><i class="fa fa-edit"></i> Edit</a>
<i class="fa fa-trash-o"></i> Delete
</td>
</tr>
<?php
}
?>
</tbody>
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);
}
});
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">  </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>