我一直在努力解决这个作业,我真的需要帮助。我真的很接近,但我被困在数据库部分。这是作业:
构建一个小型电话簿应用程序,允许您创建和删除人员。
前端应该是一个简单的页面,带有创建新人的界面。该界面应具有三个字段:名字、姓氏和电话号码以及一个提交按钮。还必须有一个人员名单。该列表应按姓氏升序排列,还应包含一个删除用户的删除按钮。删除按钮应位于列表的右侧,并且列表应根据奇数/偶数交替背景颜色。
Javascript 应该处理基本的表单验证,所有保存/删除都应该通过 AJAX 完成。
PHP 应该处理检索所有人员、在数据库中添加和删除人员。
这是我目前为止所掌握的 HTML 部分:
<div class="contact_wrapper">
<ul id="responds">
<?php
//close db connection
$mysqli->close();
?>
</ul>
<div class="form_style">
<input name="firstname_txt" id="firstnameText" cols="45" rows="5" placeholder="First Name" required></input>
</div>
<div class="form_style2">
<input name="lastname_txt" id="lastnameText" cols="45" rows="5" placeholder="Last Name" required></input>
</div>
<div class="form_style3">
<input name="phonenumber_txt" id="phonenumberText" cols="45" rows="5" placeholder="Phone Number" required></input>
</div>
<input type="submit" id="FormSubmit"></input>
<img src="images/loading.gif" id="LoadingImage" style="display:none" />
</div>
有人可以告诉我如何使用 PHP 和 AJAX/jQuery 处理输入吗?
<script type="text/javascript">
$(document).ready(function() {
//##### send add record Ajax request to response.php #########
$("#FormSubmit").click(function(e) {
e.preventDefault();
if ($("#firstnameText").val() === '') {
alert("Please enter some text!");
return false;
}
$("#FormSubmit").hide(); //hide submit button
$("#LoadingImage").show(); //show loading image
var myData = 'firstname_txt=' + $("#firstnameText").val(); //build a post data structure
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType: "text", // Data type, HTML, json etc.
data: myData, //Form variables
success: function(response) {
$("#responds").append(response);
$("#firstnameText").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
},
error: function(xhr, ajaxOptions, thrownError) {
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
alert(thrownError);
}
});
});
//##### Send delete Ajax request to response.php #########
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
var clickedID = this.id.split('-'); //Split ID string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
var myData = 'recordToDelete=' + DbNumberID; //build a post data structure
$('#firstname_' + DbNumberID).addClass("sel"); //change background of this element by adding class
$(this).hide(); //hide currently clicked delete button
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType: "text", // Data type, HTML, json etc.
data: myData, //Form variables
success: function(response) {
//on success, hide element user wants to delete.
$('#firstname_' + DbNumberID).fadeOut();
},
error: function(xhr, ajaxOptions, thrownError) {
//On error, we alert user
alert(thrownError);
}
});
});
});
</script>
在response.php中:
$firstname = $_POST['firstname_txt'];
看来您现在走在正确的道路上!
您可以像这样在 php 端访问您的帖子值:
<?php
$firstname = $_POST["firstname_txt"];
echo $firstname;
//do database stuff with $firstname.... etc.
?>
您还可以像这样在ajax请求中格式化您的
data
参数,这样如果您有更多值,则更容易阅读:
data: {
'firstname_txt': $("#firstnameText").val()
},
<?php
require("conn.php");
// Fetch departments for dropdown
$departments = $conn->query("SELECT * FROM departments");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['action']) && $_POST['action'] == 'insert') {
$salutation = $_POST['salutation'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$department_id = $_POST['department'];
$doctor_id = $_POST['doctor'];
$insert_query = "INSERT INTO patients (salutation, name, phone, email, department_id, doctor_id) VALUES ('$salutation', '$name', '$phone', '$email', '$department_id', '$doctor_id')";
if ($conn->query($insert_query) === TRUE) {
echo json_encode(['status' => 'success', 'message' => 'Record inserted successfully']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Error inserting record: ' . $conn->error]);
}
exit;
} else if (isset($_POST['edit_id'])) {
$edit_id = $_POST['edit_id'];
$salutation = $_POST['salutation'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$department_id = $_POST['department'];
$doctor_id = $_POST['doctor'];
$update_query = "UPDATE patients SET salutation = '$salutation', name = '$name', phone = '$phone', email = '$email', department_id = '$department_id', doctor_id = '$doctor_id' WHERE id = '$edit_id'";
if ($conn->query($update_query) === TRUE) {
echo json_encode(['status' => 'success', 'message' => 'Record updated successfully']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Error updating record: ' . $conn->error]);
}
exit;
} else if (isset($_POST['del_id'])) {
$id = $_POST['del_id'];
$query = "DELETE FROM patients WHERE id = $id";
if ($conn->query($query) === TRUE) {
echo json_encode(['status' => 'success', 'message' => 'Record deleted successfully']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Error inserting record: ' . $conn->error]);
}
exit;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Patient Form</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container mt-5">
<h2 class="text-center">Patient Registration</h2>
<form id="patientForm">
<div class="form-row">
<div class="form-group col-md-2">
<label for="salutation">Salutation</label>
<select id="salutation" name="salutation" class="form-control">
<option>Mr</option>
<option>Mrs</option>
<option>Ms</option>
</select>
</div>
<div class="form-group col-md-5">
<label for="name">Full Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Full Name" required>
</div>
<div class="form-group col-md-5">
<label for="phone">Phone</label>
<input type="text" class="form-control" id="phone" name="phone" placeholder="Phone Number" required>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email" required>
</div>
<div class="form-group col-md-3">
<label for="department">Department</label>
<select id="department" name="department" class="form-control">
<option value="">Select Department</option>
<?php while ($row = $departments->fetch_assoc()) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['department_name']; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group col-md-3">
<label for="doctor">Doctor</label>
<select id="doctor" name="doctor" class="form-control">
<option value="">Select Doctor</option>
</select>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<h3 class="text-center mt-5">Patient Records</h3>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
<th>Department</th>
<th>Doctor</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="patientTableBody">
<!-- Table rows to be populated via AJAX -->
</tbody>
</table>
</div>
<script>
$(document).ready(function() {
// Fetch doctors based on department
$('#department').change(function() {
var departmentId = $(this).val();
$.ajax({
url: 'fetch_doctors.php',
type: 'POST',
data: { department_id: departmentId },
success: function(data) {
$('#doctor').html(data);
}
});
});
// Submit form via AJAX
$('#patientForm').submit(function(e) {
e.preventDefault();
var action = $('#edit_id').length ? 'update' : 'insert';
$.ajax({
url: 'index.php',
type: 'POST',
data: $(this).serialize() + '&action=' + action,
success: function(response) {
var res = JSON.parse(response);
alert(res.message);
if (res.status == 'success') {
$('#patientForm')[0].reset();
loadTable(); // Reload the table
}
}
});
});
$(document).on('click', '.btn-edit', function() {
var id = $(this).data('id');
$.ajax({
url: 'fetch_patients.php',
type: 'POST',
data: { id: id },
success: function(response) {
var data = JSON.parse(response);
$('#salutation').val(data.salutation);
$('#name').val(data.name);
$('#phone').val(data.phone);
$('#email').val(data.email);
$('#department').val(data.department_id).change();
$('#doctor').val(data.doctor_id);
$('<input>').attr({
type: 'hidden',
id: 'edit_id',
name: 'edit_id',
value: id
}).appendTo('#patientForm');
}
});
});
$(document).on('click', '.btn-delete', function() {
var id = $(this).data('id');
$.ajax({
url: 'index.php',
type: 'POST',
data: $(this).serialize() + '&del_id=' + id,
success: function(response) {
var data = JSON.parse(response);
alert(data.message);
loadTable();
}
});
});
// Load patient records
function loadTable() {
$.ajax({
url: 'fetch_patients.php',
type: 'GET',
success: function(data) {
$('#patientTableBody').html(data);
}
});
}
loadTable(); // Initial table load
});
</script>
</body>
</html>
index .php