Whitespaces getting applied to input box while retrieving the data - javascript

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

Related

all dataTable pages becomes one when being refreshed via AJAX

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

How to remove value by id from JSON file?

I have small project where I need to be able to insert/edit/delete records from JSON file. I use http://myjson.com/ API for this project (not sure if this is the best solution maybe some other sources API's are better). I'm trying to remove record from json file and I'm not sure how to do that. Is there any way to do that with this API? There are instructions on how to add/update records to the json file but none on how to remove record. Here is my code example:
var contactStorage = {};
/*** Start: Build Datatables function. ***/
function buildDataTable(tblID, columnsArray, displayLength) {
$('#' + tblID).DataTable({
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
],
"iDisplayLength": displayLength,
"aoColumnDefs": [{
'bSortable': false,
'aTargets': columnsArray
}],
"language": {
"emptyTable": "No records were found."
}
});
}
/*** End: Build Datatables function. ***/
/*** Start: Phone number format for US standard. ***/
$('.us-phone').on("keypress", formatPhoneUS);
function formatPhoneUS(e) {
var output,
inputVal = $(this).val().replace(/[^0-9]/g, ''),
area = inputVal.substr(0, 3),
pre = inputVal.substr(3, 3),
tel = inputVal.substr(6, 4);
if (parseInt(inputVal, 10)) {
if (area.length < 3) {
output = "(" + area;
} else if (area.length === 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length === 3 && pre.length === 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
}
if (e.key === 'Backspace') return;
$(this).val(output);
};
/*** End: Phone number format for US standard. ***/
$("#frm_find").on("submit", findContacts);
function findContacts(e) {
e.preventDefault();
var frmFilter = $("#frm_filterby").val();
if (frmFilter) {
$.ajax({
type: 'GET',
url: 'https://api.myjson.com/bins/7iig8?' + new Date().getTime(),
dataType: 'json'
}).done(function(obj) {
contactStorage = obj.filter(function(entry) {
switch (frmFilter) {
case '1':
return entry.status === 1;
break;
case '2':
return entry.status === 0;
break;
default:
return entry;
}
});
showContacts(contactStorage);
}).fail(function(jqXHR, textStatus, errorThrown) {
alert('Error: ' + errorThrown);
});
}
}
function showContacts(contactStorage) {
var contactsTbl = "<table id='contactsTbl' class='table table-bordered'><thead><tr><th>Last</th><th>First</th><th>Email</th><th>Phone</th><th>Status</th><th class='text-center'>Edit</th><th class='text-center'>Delete</th></tr></thead><tbody>";
if (contactStorage) {
for (var key in contactStorage) {
contactsTbl += "<tr id='" + $.trim(contactStorage[key].id) + "'><td>" + $.trim(contactStorage[key].last) + "</td>";
contactsTbl += "<td>" + $.trim(contactStorage[key].first) + "</td>";
contactsTbl += "<td>" + $.trim(contactStorage[key].email) + "</td>";
contactsTbl += "<td>" + $.trim(contactStorage[key].phone) + "</td>";
contactsTbl += "<td>" + $.trim(contactStorage[key].status === 1 ? 'Active' : 'Inactive') + "</td>";
contactsTbl += "<td class='text-center'><button class='btn btn-default btn-sm contact_edit' data-toggle='collapse' data-target='#save_contact,#search_contact'><span class='glyphicon glyphicon-edit'></span></button></td>"
contactsTbl += "<td class='text-center'><button class='btn btn-default btn-sm contacts_delete'><span class='glyphicon glyphicon-remove'></span></button></td></tr>";
}
}
contactsTbl += "</tbody></table><div class='row'><div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'><div id='contact_message' class='alert message-submit'></div></div></div>";
$('#contacts_list').empty().append(contactsTbl).show();
buildDataTable('contactsTbl', [5, 6], 10);
}
var deleteID, targetTr;
$("#contacts_list").on("click", ".contacts_delete", displayContact);
function displayContact() {
deleteID = $(this).closest('tr').attr('id'), // Get record ID.
targetTr = $(this).parents('tr');
var lastName = targetTr.find("td").eq(0).text(),
firstName = targetTr.find("td").eq(1).text(),
bodyContent = $('<p>You are about to delete record for <b>' + lastName + ', ' + firstName + '</b>.<p>Do you want to proceed?</p>');
$('#delete_modalBody').empty().append(bodyContent); // Append elements to body content.
$('#deleteModal').modal('show'); // Show delete modal box.
}
$("#deleteModal").on("click", ":button.confirm_delete", removeContact);
function removeContact() {
if (deleteID) {
var table = $("#contactsTbl").DataTable(); // Select DataTable by ID.
table.row(targetTr).remove().draw(); // Remove record from DataTable.
delete contactStorage[deleteID]; // Remove element from JS object.
$("#contact_message").show().addClass("alert-success").html("Record successfully removed.").delay(5000).fadeOut('slow').queue(function() {
$(this).removeClass("alert-success").dequeue();
});
} else {
$("#contact_message").show().addClass("alert-danger").html("Error! Please contact your administrator.").delay(5000).fadeOut('slow').queue(function() {
$(this).removeClass("alert-danger").dequeue();
});
}
}
div.container {
padding-top: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Contact Application</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- *** Start: JS and CSS for DataTables. *** -->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/dataTables.jqueryui.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.print.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.jqueryui.min.css" />
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.4.2/css/buttons.dataTables.min.css" />
<!-- *** End: JS and CSS for DataTables. *** -->
<link rel="stylesheet" type="text/css" href="App.css" />
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">Welcome to Contact Application</div>
<div class="panel-body">
<div id="search_contact" class="collapse in">
<div class="row">
<div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12">
<button type="button" class="btn btn-primary" data-toggle="collapse" data-target="#save_contact,#search_contact">
<span class="glyphicon glyphicon-plus-sign"></span> New Contact
</button>
</div>
</div>
<form name="frm_find" id="frm_find" autocomplete="off">
<div class="row find-row">
<div class="form-group col-xs-12 col-sm-12 col-md-3 col-md-offset-2 col-lg-3 col-lg-offset-2">
<select class="form-control" name="frm_filterby" id="frm_filterby" required>
<option value="">--Choose--</option>
<option value="1">Active</option>
<option value="2">Inactive</option>
<option value="3">Show All</option>
</select>
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-3 col-md-offset-2 col-lg-3 col-lg-offset-2">
<button class="btn btn-block btn-primary" name="frm_search" id="frm_search">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</div>
</div>
</form>
<div id="contacts_list" class="table-responsive"></div>
</div>
<div id="save_contact" class="collapse">
<div class="row">
<div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12">
<button type="button" class="btn btn-primary" data-toggle="collapse" data-target="#save_contact,#search_contact">
<span class="glyphicon glyphicon-circle-arrow-left"></span> Go Back
</button>
</div>
</div>
<form name="frm_contacts" id="frm_contacts" autocomplete="off">
<div class="form-group">
<label class="control-label" for="fname"><span class="label label-primary">First Name:</span></label>
<input type="text" class="form-control" name="frm_first" id="frm_first" placeholder="Enter First Name" maxlength="50" title="A-Z, space, dash, apostrophe, period, comma - no other special characters" pattern="[a-zA-Z][A-Za-z' .,-]{0,49}$" required>
</div>
<div class="form-group">
<label class="control-label" for="lname"><span class="label label-primary">Last Name:</span></label>
<input type="text" class="form-control" name="frm_last" id="frm_last" placeholder="Enter Last Name" maxlength="50" title="A-Z, space, dash, apostrophe, period, comma - no other special characters" pattern="[a-zA-Z][A-Za-z' .,-]{0,49}$" required>
</div>
<div class="form-group">
<label class="control-label" for="email"><span class="label label-primary">Email address:</span></label>
<input type="email" class="form-control" name="frm_email" id="frm_email" placeholder="Enter Email" maxlength="80" required>
</div>
<div class="form-group required">
<label class="control-label" for="phone"><span class="label label-primary">Phone:</span></label>
<input type="tel" class="form-control us-phone" name="frm_phone" id="frm_phone" pattern="\(\d{3}\)[ ]?\d{3}[-]?\d{4}" maxlength="14" title="US based Phone Number in the format of: (xxx) xxx-xxxx" placeholder="(xxx) xxx-xxxx" required>
</div>
<div class="form-group required">
<label class="control-label" for="status"><span class="label label-primary">Status:</span></label>
<select class="form-control" name="frm_status" id="frm_status" required>
<option value="">--Choose--</option>
<option value="1">Active</option>
<option value="0">Inactive</option>
</select>
</div>
<div class="row">
<div class="form-group col-xs-12 col-sm-12 col-md-1 col-lg-1">
<button type="submit" name="frm_submit" id="frm_submit" class="btn btn-primary">Submit</button>
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-11 col-lg-11">
<div id="frm_message" class="alert alert-Submit"></div>
</div>
</div>
</form>
</div>
</div>
<div class="panel-footer">
<p><span>© 2018 MD. All Rights Reserved.</span></p>
</div>
</div>
</div>
<div id="deleteModal" class="modal fade" tabindex="-1" role="dialog" 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">Confirm Delete</h4>
</div>
<div class="modal-body" id="delete_modalBody"></div>
<div class="modal-footer" id="delete_modalFooter">
<button type="button" class="btn btn-warning confirm_delete" data-dismiss="modal">Delete</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
<script language="javascript" src="App.js"></script>
</body>
</html>
If anyone knows how this can be achieved or some other API's that can be used for this purpose please let me know.

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

Show email id field on selecting a particular dropdown not working

Under Label responsibility select box if i choose others then i have to get an email id input box otherwise it should be hidden. But the email id field under the div i.e showMe, is showing on selecting Individual as well as others but not supervisors. I want it show only for others.I have Tried many combinations but I have no clue why this may not be working . Any clue why this is not working?
My HTML code is:
<!-- Main content -->
<!-- Content Wrapper. Contains page content -->
<!-- Content Header (Page header) -->
<style>
tr > td
{
padding-bottom: 1em;
}
#showMe{
display:none;
}
</style>
<section class="content-header">
<h1>
Add a new checklist
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-home"></i> Home</li>
<li>My Requests</li>
<li>Resignation Requests</li>
<li class="active">Add Resignation Request</li>
</ol>
</section>
<div class="container-fluid">
<div class="row">
<!-- Thought Day-->
<div class="panel wrapper clearfix m-b-none">
<div class="panel-body">
<input type="hidden" id="page_name" value="requests">
<?php if($error_message!=''){?>
<div class="success-message <?php echo $msg_class;?>"><?php echo $error_message;?> </div>
<?php } else { ?>
<?php $row = $rows[0] ;
if(isset($row['grievance_type'])) {
$grievancetype = $row['grievance_type'];
} else { $grievancetype = ''; }
?>
<!-- form start -->
<?php echo form_open('exits/my_resignation_request/'.$id,array('name'=>'addostcstevent','id'=>'addostcstevent','method'=>'post','autocomplete'=>'on','class'=>'form-horizontal'))?>
<?php echo form_hidden(array('id'=>$row->id,'action'=>$action));?>
<div class="box-body">
<input type="hidden" name="todays_date" readonly id="todays_date" value="<?php echo date('m/d/y');?>" class="form-control col-md-10" <?php if($USER->permissions[0] != 'all') { ?> readonly <?php } ?>>
<table>
<tr>
<td>
Action Item
</td>
<td>
<input placeholder="Action Item" class=" m-wrap col-md-8 form-control " id="action" type="text" name="action" value="" required/>
</td>
</tr>
<tr>
<td>
Category
</td>
<td>
<select class="default" id="category" name="category">
<option name="exit_type" value="" selected>Select a option</option>
<option name="exit_type" value="Managers">Managers</option>
<option name="exit_type" value="Admins">Admins</option>
<option name="exit_type" value="Employees">Employees</option>
</select>
</td>
</tr>
<tr></tr>
<tr>
<td>
<label>Responsibility</label>
</td>
<td>
<select class="default" id="security_question" name="exit_type">
<option name="exit_type" value="" selected>Select a option</option>
<option name="exit_type" value="Individual">Individual</option>
<option name="exit_type" value="Supervisors">Supervisors</option>
<option name="exit_type" value="others">others</option>
</select>
</td>
</tr>
<tr>
<td>
<label>Timelines for completion</label>
</td>
<td>
<div class="date" data-date="12-02-2012" data-date-format="mm-dd-yyyy" data-date-viewmode="years">
<input placeholder="Last working day" class=" m-wrap col-md-8 form-control " id="startdt" type="text" name="requested_date" value="<?php if($row->requested_date!='') echo date("d-m-Y",$row->requested_date); ?>" required/>
</td>
</tr>
</table>
<div id="showMe">
<table>
<tr>
<td>
Email ID
</td>
<td>
<input placeholder="Email" class=" m-wrap col-md-8 form-control " id="email" type="text" name="email" value="" required/>
</td>
</tr>
</table>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<?php
echo form_hidden('action',$action);
echo form_hidden('id',$id);
?>
<!--<button type="submit" class="btn btn-info pull-right" name="withdraw" style="margin:0px 10px" value="withdrawn">Withdraw Resignation</button>-->
<button type="submit" class="btn btn-info pull-right" style="margin:0px 10px">Submit</button>
</div><!-- /.box-footer -->
</form>
<?php } ?>
</div><!-- /.box -->
</div><!--/.col (right) -->
</div> <!-- /.row -->
<div class="modal fade" role="dialog" id="myLTAModal">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Alert!</h4>
</div>
<div class="modal-body">
<!-- modal content-->
<div class="panel-body">
<p>Ensure you refer to LTA guidelines before planning your trip. You will be required to submit your tickets as proof to avail LTA.</p>
</div>
</div>
<!-- modal content-->
</div>
</div>
</div>
<div class="modal fade" role="dialog" id="leaveAllowedModal">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Alert!</h4>
</div>
<div class="modal-body">
<!-- modal content-->
<div class="panel-body">
<p class="allowed_text"></p>
</div>
</div>
<!-- modal content-->
</div>
</div>
</div>
</section><!-- /.content -->
<script>
/*$(document).ready(function(){
$('#reservation').daterangepicker();
})*/
</script>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/plugins/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
<script>
var elem = document.getElementById("security_question");
elem.onchange = function(){
var hiddenDiv = document.getElementById("showMe");
hiddenDiv.style.display = (this.value == "Individual") ? "none":"none";
hiddenDiv.style.display = (this.value == "Supervisors") ? "none":"block";
hiddenDiv.style.hidden = (this.value == "others") ? "none":"none";
};
function parseDate(str) {
var mdy = str.split('/')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daydiff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
$(document).ready(function(){
$("#startdt").datepicker({
dateFormat: 'dd-mm-yy',
changeMonth: true,
changeYear: true,
showButtonPanel: true,
yearRange: "-90:+0",
startDate: new Date(),
autoclose: true
}).on('changeDate', function (selected) {
var minDate = new Date(selected.date.valueOf());
$('#enddt').datepicker('setStartDate', minDate);
});
$("#enddt").datepicker({
dateFormat: 'dd-mm-yy',
changeMonth: true,
changeYear: true,
showButtonPanel: true,
yearRange: "-90:+0"
});
$("#enddt").change(function(){
if($("#startdt").val()!='' && $("#enddt").val()!='')
{
var startdt = $("#startdt").val();
var enddt = $("#enddt").val();
$("#daysleave").val(daydiff(parseDate(startdt), parseDate(enddt)));
if($("#grievance_type").val()!='0')
{
var day_diff_today = daydiff(parseDate($("#today_dt").val()), parseDate($("#startdt").val()));
if(((parseInt($("#daysleave").val()) > parseInt($("#grievance_type option:selected").attr("data-min"))) && (parseInt($("#daysleave").val()) < parseInt($("#grievance_type option:selected").attr("data-max"))))&&(day_diff_today > parseInt($("#grievance_type option:selected").attr("data-approvaldays"))))
{ } else {
$("#leaveAllowedModal").modal("show");
}
}
}
})
$("#grievance_type").change(function(){
if($("#startdt").val()!='' && $("#enddt").val()!='' && $("#grievance_type").val()!='0')
{
var day_diff_today = daydiff(parseDate($("#today_dt").val()), parseDate($("#startdt").val()));
if(((parseInt($("#daysleave").val()) > parseInt($("#grievance_type option:selected").attr("data-min"))) && (parseInt($("#daysleave").val()) < parseInt($("#grievance_type option:selected").attr("data-max"))))&&(day_diff_today > parseInt($("#grievance_type option:selected").attr("data-approvaldays"))))
{ } else {
$("#leaveAllowedModal").modal("show");
}
}
})
$(".date-picker").datepicker();
$("#optionsRadios1").click(function(){
$("#myLTAModal").modal("show");
})
$('#leaveAllowedModal').on('shown.bs.modal', function() {
var msg = '';
if((parseInt($("#daysleave").val()) > parseInt($("#grievance_type option:selected").attr("data-min"))) && (parseInt($("#daysleave").val()) < parseInt($("#grievance_type option:selected").attr("data-max"))))
{ } else {
msg = msg + "You wish you apply "+$("#daysleave").val()+" day of "+$("#grievance_type option:selected").text()+". Minimum and Maximum no. of Leaves allowed to take at a time are "+$("#grievance_type option:selected").attr("data-min")+" and "+$("#grievance_type option:selected").attr("data-max")+" respectively.";
}
var day_diff_today = daydiff(parseDate($("#today_dt").val()), parseDate($("#startdt").val()));
if((day_diff_today < parseInt($("#grievance_type option:selected").attr("data-approvaldays"))))
{
msg = msg + " No. of days of prior approval needed is " + $("#grievance_type option:selected").attr("data-approvaldays") + " days";
}
$(".allowed_text").html(msg);
})
});
</script>
You do not use to write the code for every data element. Just use the below one.
Javascript :
hiddenDiv.className = ((this.value == "others") ? "showDiv":"hideDiv");
CSS :
.showDiv{
display:block;
}
.hideDiv{
display:none;
}
html : <div id="showMe" class="hideDiv">

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