Отправка формы через ajax завершена. Загрузка записи таблицы html из базы данных через ajax также завершена. Моя проблема заключается в том, что модальная строка, генерируемая каждой строкой таблицы html, не отвечает при отправке формы. Моя цель состоит в том, чтобы он не перезагрузил страницу даже при обновлении записи, потому что моя запись состоит из нескольких вкладок bootstrap. У меня нет проблем с обновлением формы, которая находится внутри текущей страницы, но я не могу понять, почему форма внутри модальной загрузки через ajax не отвечает.
Вот моя основная запись html таблица на главной странице:
<table class="table table-hover m-b-0 c_list">
<thead class="thead-light">
<tr>
<th>Employee ID</th>
<th>Name of Employee</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$qusr = $dbcbcs->query("SELECT * FROM tblhr ORDER BY pkid DESC");
while($rusr = $qusr->fetch_assoc())
{
echo '<tr>
<td style="padding: .25rem;">' . $rusr["prfno"] . '</td>
<td style="padding: .25rem;">' . $rusr["fname"] . ' ' . $rusr["lname"] . '</td>
<td style="padding: .25rem;">
<a href="somepage.php?view=' . $rusr["pkid"] . '" class="btn btn-info" title="Edit"><i class="fa fa-edit"></i></a>
</td>
</tr>';
}
?>
</tbody>
</table>
Если я выберу запись из моей основной таблицы, это будет вид на вкладках моего меню:
<ul class="nav nav-tabs-new2">
<li class="nav-item"><a class="nav-link active show" data-toggle="tab" href="#personal">Personal Data</a></li>
<?php if (isset($_GET['view'])) { ?>
<li class="nav-item"><a class="nav-link" data-toggle="tab" href="#education">Educational Attainment</a></li>
<li class="nav-item"><a class="nav-link" data-toggle="tab" href="#history">Employment History</a></li>
<input type="hidden" name="hrprimarykey" id="hrprimarykey" value="<?php echo $_GET['view']; ?>" />
<?php } else { ?>
<li class="nav-item"><a class="nav-link">Educational Attainment</a></li>
<li class="nav-item"><a class="nav-link">Employment History</a></li>
<input type="hidden" name="hrprimarykey" id="hrprimarykey" value="" />
<?php } ?>
</ul>
<div class="tab-content">
<div class="tab-pane show active" id="personal">
<h6>PERSONAL DATA</h6>
<?php if (isset($_GET['view']))
{
$person_id = $_GET['view'];
$qprf = $dbcbcs->query("SELECT * FROM tblhr WHERE pkid = '$person_id'") or die("Query fail on edit: " . $dbc->error);
$rprf = $qprf->fetch_assoc();
?>
<form method="post" action="" id="edit-peronal">
<div class="body">
<div class="row clearfix">
<div class="col-lg-6 col-md-6 col-sm-12">
<div class="input-group input-group-sm mb-1">
<div class="input-group-prepend">
<span class="input-group-text" style="font-size:12px;font-weight:800;">Employee ID</span>
</div>
<input type="text" class="form-control" name="eeenoid" id="eeenoid" value="<?php echo $rprf['bhtprfno']; ?>" readonly>
</div>
</div>
<div class="col-lg-4 col-md-6 col-sm-12">
<div class="input-group input-group-sm mb-1">
<div class="input-group-prepend">
<span class="input-group-text" style="font-size:12px;font-weight:800;">First Name</span>
</div>
<input type="text" class="form-control" name="efname" id="efname" value="<?php echo $rprf['bhtfname']; ?>">
</div>
</div>
<div class="col-lg-4 col-md-6 col-sm-12">
<div class="input-group input-group-sm mb-1">
<div class="input-group-prepend">
<span class="input-group-text" style="font-size:12px;font-weight:800;">Last Name</span>
</div>
<input type="text" class="form-control" name="elname" id="elname" value="<?php echo $rprf['bhtlname']; ?>">
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12" style="text-align:right;">
<input type="hidden" name="personalid" id="personalid" value="<?php echo $rprf['bhtid']; ?>">
<button id="UpdatePersonal" class="btn btn-outline-info"><i class="fa fa-save"></i> Update</button>
<a href="hr-201-view.bcs" class="btn btn-outline-danger"><i class="fa fa-refresh"></i> Cancel</a>
</div>
</div>
</div>
</form>
<?php } ?>
</div>
<div class="tab-pane" id="education">
<h6>EDUCATIONAL BACKGROUND</h6>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" id="new-educ">
<div class="body">
<div class="row clearfix" id="formedu">
<div class="col-lg-3 col-md-6 col-sm-12">
<div class="input-group input-group-sm mb-1">
<div class="input-group-prepend">
<span class="input-group-text" style="font-size:12px;font-weight:800;">Level <b style="color:#ff0000;">*</b></span>
</div>
<select name="edulevel" id="edulevel" class="custom-select" style="height: calc(1.80rem + 2px);padding: .325rem 1.75rem .375rem .75rem;" required>
<option>Primary</option>
<option>Secondary</option>
<option>Vocational</option>
<option>Tertiary</option>
<option>Graduate Studies</option>
</select>
</div>
</div>
<div class="col-lg-3 col-md-6 col-sm-12">
<div class="input-group input-group-sm mb-1">
<div class="input-group-prepend">
<span class="input-group-text" style="font-size:12px;font-weight:800;">Year Graduated <b style="color:#ff0000;">*</b></span>
</div>
<select name="eduyr" id="eduyr" class="custom-select" style="height: calc(1.80rem + 2px);padding: .325rem 1.75rem .375rem .75rem;" required>
<?php
for($year=$yearfirst;$year<=$yearend;$year++)
{
echo "<option value='$year'>$year</option>";
}
?>
</select>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<div class="input-group input-group-sm mb-1">
<div class="input-group-prepend">
<span class="input-group-text" style="font-size:12px;font-weight:800;">Institution <b style="color:#ff0000;">*</b></span>
</div>
<input type="text" class="form-control" name="eduschool" id="eduschool" required>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12" style="text-align:right;">
<input type="hidden" class="form-control" name="eeducid" id="eeducid" value="<?php echo $_GET['view']; ?>">
<button type="submit" name="SaveEducation" id="SaveEducation" class="btn btn-outline-success"><i class="fa fa-save"></i> Save</button>
<button type="reset" class="btn btn-outline-danger"><i class="fa fa-refresh"></i> Cancel</button>
</div>
</div>
</div>
</form>
<div class="body">
<div class="row clearfix">
<div id="loadeducationpreview" style="width:100%;">
</div>
</div>
</div>
</div>
<div class="tab-pane" id="history">
<h6>EMPLOYMENT HISTORY</h6>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" id="new-emphistory">
<div class="body">
<div class="row clearfix" id="formemph">
<div class="col-lg-6 col-md-6 col-sm-12">
<div class="input-group input-group-sm mb-1">
<div class="input-group-prepend">
<span class="input-group-text" style="font-size:12px;font-weight:800;">Company <b style="color:#ff0000;">*</b></span>
</div>
<input type="text" class="form-control" name="companyh" id="companyh">
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<div class="input-group input-group-sm mb-1">
<div class="input-group-prepend">
<span class="input-group-text" style="font-size:12px;font-weight:800;">Position <b style="color:#ff0000;">*</b></span>
</div>
<input type="text" class="form-control" name="positionh" id="positionh">
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12" style="text-align:right;">
<input type="hidden" class="form-control" name="eemphid" id="eemphid" value="<?php echo $_GET['view']; ?>">
<button type="submit" name="SaveEmpHistory" id="SaveEmpHistory" class="btn btn-outline-success"><i class="fa fa-save"></i> Save</button>
<button type="reset" class="btn btn-outline-danger"><i class="fa fa-refresh"></i> Cancel</button>
</div>
</div>
</div>
<div class="body">
<div class="row clearfix">
<div id="loademphistorypreview" style="width:100%;">
</div>
</div>
</div>
</form>
</div>
</div>
Вот мой javascript, который загружает таблицу в div и отправку формы из новой записи
<script type="text/javascript">
$(document).ready(function()
{
//get the id from URL and pass to input tag
if($('#hrprimarykey').val() === '')
{
$("#loadeducationpreview").empty();
$("#loademphistorypreview").empty();
}
else
{
var dataString = document.getElementById('hrprimarykey').value;
$.ajax({ type: "POST", url: "_hr-education.php", data: { dataString: dataString }, success: function(html) { $("#loadeducationpreview").html(html); } }); return false;
$.ajax({ type: "POST", url: "_hr-employmenthistory.php", data: { dataString: dataString }, success: function(html) { $("#loademphistorypreview").html(html); } }); return false;
}
});
$(document).ready(function()
{
var form = $('#edit-personal');
var submit = $('#UpdatePersonal');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '_hr_personel_updates.php', type: 'POST', dataType: 'html', data: form.serialize(), success: function(data)
{
alert('Personnel Data updates!');
}, error: function(e) { alert('Sorry. An error occur.'); }
});
});
});
$(document).ready(function()
{
var form = $('#new-educ');
var submit = $('#SaveEducation');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '_hr_education_saving.php', type: 'POST', dataType: 'html', data: form.serialize(), success: function(data)
{
alert('New Education Attainment is saved!');
$.each($('#formedu input'), function(idx, input){ $(input).val(''); });
$('#edulevel option').each(function () { if (this.defaultSelected) { this.selected = true; return false; } });
$('#eduyr option').each(function () { if (this.defaultSelected) { this.selected = true; return false; } });
var dataString = document.getElementById('hrprimarykey').value;
$.ajax({ type: "POST", url: "_hr-education.php", data: { dataString: dataString }, success: function(html) { $("#loadeducationpreview").html(html); } }); return false;
}, error: function(e) { alert('Sorry. An error occur.'); }
});
});
});
$(document).ready(function()
{
//------------------------ this won't work, I wonder why but the process is almost similar on submitting new entry
var form = $('#edit-educ');
var submit = $('#UpdateEducation');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '_hr_education_updates.php', type: 'POST', dataType: 'html', data: form.serialize(), success: function(data)
{
alert('Education Attainment updates!');
var dataString = document.getElementById('hrprimarykey').value;
$.ajax({ type: "POST", url: "_hr-education.php", data: { dataString: dataString }, success: function(html) { $("#loadeducationpreview").html(html); } }); return false;
}, error: function(e) { alert('Sorry. An error occur.'); }
});
});
});
</script>
Что касается страницы, которая загружает таблицу html, которая включает в себя модальный (_hr-education. php) и основная проблема для отправки формы:
<?php
session_start();
include("dbconn.php");
if(isset($_POST['dataString']) && $_POST['dataString'] != '')
{
$educ_foreignkey = $_POST['dataString'];
echo '
<div class="table-responsive shadow p-3 mb-5 bg-white rounded">
<table class="table table-hover m-b-0 c_list">
<thead style="background: #28a745;color: #fff;">
<tr>
<th style="padding: .40rem .20rem;">Level</th>
<th style="padding: .40rem .20rem;">Institution</th>
<th style="padding: .40rem .20rem;">Yr Graduated</th>
<th style="padding: .40rem .20rem;">Action</th>
</tr>
</thead>
<tbody>';
$qedu = $dbcbcs->query("SELECT * FROM tbleducation WHERE fkid LIKE '$educ_foreignkey' ORDER BY yrgrad ASC");
while($redu = $qedu->fetch_assoc())
{
echo '<tr>
<td style="padding: .20rem;">' . $redu["lvl"] . '</td>
<td style="padding: .20rem;">' . $redu["someschool"] . '</td>
<td style="padding: .20rem;">' . $redu["yrgrad"] . '</td>
<td style="padding: .20rem;">
<a data-toggle="modal" data-target="#education-'. $redu["pkid"] .'" class="btn btn-info btn-sm" style="color:#fff;"><i class="fa fa-pencil"></i> Edit</a>
</td>
</tr>';
echo '
<div id="education-'.$redu["pkid"].'" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="homeslidelabel">
<div class="modal-dialog modal-md" role="document">
<div class="modal-content">
<div class="modal-header"><h4 class="title" id="largeModalLabel">Edit Educational Attainment</h4></div>
<div class="modal-body">';
?>
<form method="post" action="" id="edit-educ">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Level</span>
</div>
<select name="eedulevel" id="eedulevel" class="custom-select" style="height: calc(1.80rem + 2px);padding: .325rem 1.75rem .375rem .75rem;">
<option value="Primary" <?php if ($redu['lvl'] == 'Primary') echo 'selected="selected"'; ?>>Primary</option>
<option value="Secondary" <?php if ($redu['lvl'] == 'Secondary') echo 'selected="selected"'; ?>>Secondary</option>
<option value="Vocational" <?php if ($redu['lvl'] == 'Vocational') echo 'selected="selected"'; ?>>Vocational</option>
<option value="Tertiary" <?php if ($redu['lvl'] == 'Tertiary') echo 'selected="selected"'; ?>>Tertiary</option>
<option value="Graduate Studies" <?php if ($redu['lvl'] == 'Graduate Studies') echo 'selected="selected"'; ?>>MaGraduate Studiesle</option>
</select>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Year</span>
</div>
<select name="eeduyr" id="eeduyr" class="custom-select" style="height: calc(1.80rem + 2px);padding: .325rem 1.75rem .375rem .75rem;">
<?php
$editfryr = $redu['yrgrad'];
?>
<option value="<?php echo $editfryr; ?>" <?php if ($redu['yrgrad'] == '$editfryr') echo 'selected="selected"'; ?>><?php echo $editfryr; ?></option>
<?php
for($year=$yearfirst;$year<=$yearend;$year++)
{
echo "<option value='$year'>$year</option>";
}
?>
</select>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="input-group input-group-sm mb-1">
<div class="input-group-prepend">
<span class="input-group-text" style="font-size:12px;font-weight:800;">Institution</span>
</div>
<input type="text" class="form-control" name="eeduschool" id="eeduschool" value="<?php echo $redu['someschool']; ?>">
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12" style="text-align:right;">
<input type="hidden" class="form-control" name="efkid" id="efkid" value="<?php echo $redu['fkid']; ?>">
<input type="hidden" name="epkid" id="epkid" value="<?php echo $redu['pkid']; ?>">
<button type="submit" id="UpdateEducation" name="UpdateEducation" class="btn btn-outline-primary"><i class="fa fa-save"></i> Update</button>
</div>
</form>
<?php
echo '
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-danger" data-dismiss="modal"><i class="fa fa-close"></i> CLOSE</button>
</div>
</div>
</div>
</div>
</tr>';
}
echo '</tbody>
</table>';
}
?>
и, наконец, эта страница, которая запускает обновление записей (_hr_education_updates. php):
<?php
session_start();
include("dbconn.php");
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ) {
$editlvl = $_POST["eedulevel"];
$edityr = $_POST["eeduyr"];
$editskol = $_POST["eeduschool"];
$uppk_id = $_POST["epkid"];
$sql = $dbcbcs->query("UPDATE tbleducation SET lvl='$editlvl', yrgrad='$edityr', someschool='$editskol' WHERE pkid='$uppk_id'") or die("Edit Query: " . $dbc->error);
}
?>
Спасибо, что уделили время на чтение моей проблемы.