all dataTable pages becomes one when being refreshed via AJAX - javascript

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

Related

Ajax function run multiple times on modal close and open

I have a form in my modal and I submit the form it submits the data and then fetches the saved data using ajax function. The problem is that, When I close the modal and re opens it and submit the form: the ajax call run twice and thrice if close the modal again reopens again submit again and so on so forth. It works fine when the modal is kept open. The ajax calls runs only once no matter how many times the form is submitted.
I have tried resetting the form in modal on close but nothing worked.
// location.reload(true);
$('#custgroupAssign').val('');
$('#varAssign').val('');
$('#assignStock').val('');
$('#assignPrice').val('');
});
<div id="assignment_model" class="modal fade">
<div class="modal-dialog modal-lg">
<div class="modal-content ">
<div class="modal-header">
<h4 class="modal-title"><?php echo $this->lang->line('Assign Products') ?></h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
</div>
<div class="modal-body" id="assignment_object">
<form method="post" id="assignment_form" enctype="multipart/form-data">
<tr>
<th>Product:</th>
<td colspan="5">
<h3><?php echo $product['product_name']; ?></h3>
<input type="hidden" id="pid" value="<?= $product['pid'] ?>">
</td>
</tr>
<tr>
<?php if ($product_variations){ ?>
<th>Select Variation</th>
<td colspan="4"><select id="varAssign" class="form-control required">
<option value="">Select</option>
<?php
foreach ($product_variations as $product_variation) {
echo "<option value='".$product_variation['vb']."'>".$product_variation['name']." </option>";
}
?>
</select>
<?php
foreach ($product_variations as $product_variation) {
echo "<input type='hidden' id='qty-".$product_variation['vb']."' value='".$product_variation['qty']."'/>";
}
?>
</td>
<input type="hidden" id="pid" value="<?= $product['pid'] ?>">
<?php } ?>
</tr>
<tr>
<th>Customer Group/var </th>
<th></th>
<th>Stock*</th>
<th>Price*</th>
<th></th>
</tr>
<tr>
<td colspan="2"><select id="custgroupAssign" class="form-control required">
<option value="">Select</option>
<?php
foreach ($cust_groups as $cust_group) {
echo "<option value='".$cust_group['id']."'>".$cust_group['title']." </option>";
}
?>
</select>
</td>
<td><input value="" class="form-control required" id="assignStock">
</td>
<td><input value="" class="form-control" id="assignPrice"
placeholder="<?php echo $this->lang->line('Product Price') ?>">
</td>
<td>
<!-- <button class="btn btn-blue tr_delete">Assign</button>-->
<input type="submit" id="assign-product" class="btn btn-blue margin-bottom"
value="Assign" data-loading-text="Adding...">
<input type="hidden" value="products/assignproduct" id="assignment-url">
</td>
</tr>
</form>
</div>
<div class="modal-footer">
<input type="hidden" id="assignment-object-id" value="">
<input type="hidden" id="assignment-action-url" value="products/assign_products">
<button type="button" data-dismiss="modal"
class="btn"><?php echo $this->lang->line('Close') ?></button>
</div>
</div>
</div>
</div>
$(document).on('click', "#assign-product", function (e) {
e.preventDefault();
jQuery.ajax({
url: baseurl + url,
type: 'POST',
cache: false,
data: 'pid=' + pid + '&custgroupAssign=' + custgroupAssign + '&varAssign=' + varAssign + '&assignStock=' + assignStock + '&assignPrice=' + assignPrice + '&' + crsf_token + '=' + crsf_hash,
dataType: 'json',
success: function (data) {
$('#custgroupAssign').val('');
$('#varAssign').val('');
$('#assignStock').val('');
$('#assignPrice').val('');
var assignedproducts = data.products;
$('#assigned-product-list tbody').empty();
for (var key in assignedproducts) {
var currency = '<?= amountExchange('', 0, $this->aauth->get_user()->loc); ?>';
$('#assigned-product-list tbody').append('<tr><td>'+ assignedproducts[key].product_name +'</td><td>'+ assignedproducts[key].variation +'</td><td>'+ assignedproducts[key].name +'</td><td>'+ assignedproducts[key].stock +'</td><td>'+ currency + assignedproducts[key].product_price +'</td><td><a data-product-id="'+ assignedproducts[key].id +'" class="btn btn-sm btn-danger rmAssgined">X</a></td></tr>');
}
},
error: function (xhr, status, error) {
error_div.append('<div class="alert alert-warning alert-dismissible fade show" role="alert">' + xhr.responseText + '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button></div>');
}
});
});

Whitespaces getting applied to input box while retrieving the data

I am designing a application in PHP and using javascript to perform add/edit/delete .The data is getting inserted correctly but when i click on edit button the data dispalyed is in the centre if input box. i tried using CSS but nothing happened. I am also not able to type in either to correct the mistake.Below is code
PHP:
<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<head>
<?php include_once("header.php"); ?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" integrity="sha256-p6xU9YulB7E2Ic62/PX+h59ayb3PBJ0WFTEQxq0EjHw=" crossorigin="anonymous" />
</head>
<!-- END HEAD -->
<body class="page-header-fixed page-sidebar-closed-hide-logo page-container-bg-solid page-content-white">
<div class="page-wrapper">
<?php include_once("navbar.php"); ?>
<!-- BEGIN HEADER & CONTENT DIVIDER -->
<div class="clearfix">
</div>
<!-- END HEADER & CONTENT DIVIDER -->
<!-- BEGIN CONTAINER -->
<div class="page-container">
<?php include_once("side_bar.php"); ?>
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<div class="page-content">
<button class="btn btn-success mt-sweetalert hide" data-title="Sweet Alerts with Icons" data-message="Success Icon" data-type="success" data-allow-outside-click="true" data-confirm-button-class="btn-success" id="msgbox" >Icon Success Alert</button>
<button class="btn btn-warning mt-sweetalert hide" data-title="Sweet Alerts with Icons" data-message="Warning Icon" data-type="warning" data-allow-outside-click="true" data-confirm-button-class="btn-warning" id="wmsg">Icon Warning Alert</button>
<a class="btn green btn-outline sbold" data-toggle="modal" href="#draggable"> + Add Assessment Type </a>
<div class="table-responsive">
<table id="users" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th style="display:none;">ID</th>
<th onclick="sortTable(1)">Assessment type code</th>
<th onclick="sortTable(2)">Assessment Name</th>
<th colspan="2">Actions</th>
</tr>
</thead>
<tbody id="table_body">
<tr>
<th style="display:none;">ID</th>
<th>
<input type="text" class="form-control" id="codes" onkeyup="myFunction(this.id, 1)" placeholder="Search for codes.." title="Type in a name">
</th>
<th>
<input type="text" class="form-control" id="names" onkeyup="myFunction(this.id, 2)" placeholder="Search for names.." title="Type in a name">
</th>
<th colspan="2"></th>
</tr>
<?php
include_once PHP_PATH .'/config.php';
$sql = "select * from list_assessment_types";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
$aid = $row["pk_assess_type_id"];
$code = $row["assess_type_code"];
$name = $row["assess_type_name"];
?>
<tr id="<?php echo $aid ?>">
<td style="display:none;"></td>
<td>
<?php echo $code ?>
</td>
<td>
<?php echo $name ?>
</td>
<td><a name="edit" class="btn blue btn-outline sbold" data-toggle="modal" href="#draggable1"><i class="fa fa-pencil-square-o fa-1x" aria-hidden="true"></i> Edit</a>
</td>
<td><button name="del" class="btn red btn-outline sbold"><i class="fa fa-trash fa-1x" aria-hidden="true"></i> Delete</button>
</td>
</tr>
<?php
}
db_close();
?>
</tbody>
</table>
</div>
<!-- Modal to add assessment type-->
<div class="modal fade draggable-modal" id="draggable" tabindex="-1" role="basic" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Add new Assessment Type</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="code">Assessment type code</label>
<input type="text" name="code" maxlength="15" id="code" value="" class="form-control" />
</div>
<div class="form-group">
<label for="name">Assessment name</label>
<input type="text" name="name" id="name" maxlength="20" value="" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button id="new_save" type="button" class="btn green" data-dismiss="modal">Save changes</button>
<button type="button" class="btn dark btn-outline" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- Modal finishes here-->
<!-- Modal to edit assessment type-->
<div class="modal fade draggable-modal" id="draggable1" tabindex="-1" role="basic" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Edit Assessment Type</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="e_code">Assessment type code</label>
<input type="text" name="e_code" maxlength="15" id="e_code" value="" placeholder="test" class="form-control" />
</div>
<div class="form-group">
<label for="e_name">Assessment name</label>
<input type="text" name="e_name" id="e_name" maxlength="20" value="" placeholder="test" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button id="e_save" type="button" class="btn green" data-dismiss="modal">Save changes</button>
<button type="button" class="btn dark btn-outline" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- Modal finishes here-->
</div>
<!-- END QUICK SIDEBAR -->
</div>
</div>
<!-- END CONTAINER -->
<?php include_once("footer_text.php"); ?>
</div>
<div class="quick-nav-overlay"></div>
<?php include_once("footer.php"); ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
<script type="text/javascript" src="<?= ASSET_PATH ?>assets/staff_js/assessment_type.js"></script>
<script>
function myFunction(tab, s) {
var input, filter, table, tr, td, i;
input = document.getElementById(tab);
filter = input.value.toUpperCase();
table = document.getElementById("users");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[s];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
<script>
$("#draggable").draggable({
handle: ".modal-header"
});
</script>
</body>
</html>
JS
var x, okay_content, idx;
$(function () {
var parentId, tr;
$('#new_save').click(function () {
var code = $('#code').val();
var name = $('#name').val();
$.ajax({
url: 'class_codes.php',
type: 'post',
dataType: 'json',
data: {
from: 'insert',
code: code,
name: name
},
success: function (response) {
// Check if data is redundant.
if (response[0] === "REDUNDANT") {
alert("Data already exist.");
} else if (response[0] === "EMPTY") {
alert("Field can't be left empty");
} else if (response[0] == "1")
{
// Insert or Edit
$("#users tbody").append("<tr id=" + response[1] + "><td style='display:none;'><td>" + code + "</td>" + "<td>" + name + "</td>" + "<td><a name= 'edit' href='' class='btn blue btn-outline sbold'><i class='fa fa-pencil-square-o fa-1x' aria-hidden='true'></i> Edit</a></td><td><button name='del' class='btn red btn-outline sbold'><i class='fa fa-trash fa-1x' aria-hidden='true'></i> Delete</button></td></tr>");
//sortTable(1);
alert("Class Code created successfully.");
return false;
} else {
alert("Error: " + response[0]);
}
},
error: function (error) {
okay_content = error[0];
$("#okay").dialog("open");
}
});
});
$(document).on('click', 'a[name="edit"]', function () {
tr = $(this).parents('tr');
$('#e_code').val(tr.find("td:eq(1)").text());
$('#e_name').val(tr.find("td:eq(2)").text());
parentId = tr.attr('id');
});
$(document).on('click', '#e_save', function () {
var code = $('#e_code').val();
var name = $('#e_name').val();
alert("CODE: " + code + " NAME: " + name + " ID: " + parentId);
$.ajax({
url: 'assessment_type.php',
type: 'post',
dataType: 'json',
data: {
from: 'edit',
id: parentId,
code: code,
name: name
},
success: function (response) {
// Check if data is redundant.
if (response[0] === "REDUNDANT") {
alert("Data already exist.");
} else if (response[0] === "EMPTY") {
alert("Field can't be left empty");
// Check if field is empty
// okay_content = "Field can't be left empty ";
} else if (response[0] == "1")
{
// Insert or Edit
tr.remove();
$("#users tbody").append("<tr>" + "<td style='display:none;'>" + response[1] + "<td>" + code + "</td>" + "<td>" + name + "</td>" + "<td><a href='' class='btn blue btn-outline sbold'><i class='fa fa-pencil-square-o fa-1x' aria-hidden='true'></i> Edit</a></td>" + "<td><button name='del' class='btn red btn-outline sbold'><i class='fa fa-trash fa-1x' aria-hidden='true'></i> Delete</button></td></tr>");
//sortTable(1);
alert("Class Code edited successfully.");
return false;
} else {
alert("Error: " + response[0]);
}
},
error: function (error) {
okay_content = error[0];
$("#okay").dialog("open");
}
});
});
$(document).on('click', 'button[name="del"]', function () {
var row = $(this).parents('tr');
var id = row.attr('id');
$.ajax({
url: 'class_codes.php',
type: 'post',
dataType: 'json',
data: {
id: id,
from: 'delete'
},
success: function (suc) {
if (suc[0] == "1") {
alert("Class Code deleted successfully.");
$(this).addClass('btn-success ')
row.fadeOut(1000);
}
},
error: function (error) {
alert(error);
}
});
});
});
I am not sure where I am going wrong. Looks like the issue is within JS as I havbe tried turning entore CSS off but the issue still persists. Help please !!!
the php eho statement should be in 1 line

How to multiple update rows with modal bottstrap

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/

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