我有一个带有 TMForm.js 和 MailHandler.php 的联系表单,效果很好。
现在我想在同一 html 页面上添加另一个联系表单,并且我想在我将从提交中收到的电子邮件中标识第二个表单。
问题是仅适用于第一种形式。我该如何解决这个问题?
这是我的代码: HTML:
<form id="contact-form" method="post" action="bat/MailHandler.php">
<div class="success_wrapper">
<div class="success-message">Il messaggio è stato inviato
con successo. Sarai contattato al più presto.</div>
</div>
<label class="name"> <input placeholder="Nome*:" data-constraints="@Required @JustLetters"
type="text"> <span class="empty-message">*Questo campo è
obbligatorio.</span> <span class="error-message">*Nome
non valido. Inserisci un nome valido.</span> </label>
<label class="email"> <input placeholder="E-mail*:" data-constraints="@Required @Email"
type="text"> <span class="empty-message">*Questo campo è
obbligatorio.</span> <span class="error-message">*E-mail
non valido. Inserisci un e-mail valido.</span> </label> <label
class="phone"> <input placeholder="Telefono:" data-constraints="@Required @JustNumbers"
type="text"> <span class="empty-message">*Questo campo è
obbligatorio.</span> <span class="error-message">*Numero
di telefono non valido. Inserisci un numero valido</span>
</label> <label class="message"> <textarea placeholder="Messaggio*:"
data-constraints="@Required @Length(min=20,max=999999)" style="height: 72px"></textarea>
<span class="empty-message">*Questo campo è obbligatorio.</span>
<span class="error-message">*Il messaggio è troppo corto.</span>
</label>
<div>
<div class="btn"> <a class="def-btn btn1" href="#" data-type="submit">INVIA
RICHIESTA</a>
<p class="fields">*Campi
obbligatori</p>
</div>
</div>
</form>
这是TMform.js:
//TMForm
(function($){
$.fn.TMForm=function(opt){
return this.each(TMForm)
function TMForm(){
var form=$(this)
opt=$.extend({
okClass:'ok'
,emptyClass:'empty'
,invalidClass:'invalid'
,successClass:'success'
,onceVerifiedClass:'once-verified'
,mailHandlerURL:'bat/MailHandler.php'
,successShowDelay:'20000'
,stripHTML:true
},opt)
init()
function init(){
form
.on('submit',formSubmit)
.on('reset',formReset)
.on('focus','[data-constraints]',function(){
$(this).parents('label').removeClass(opt.emptyClass)
})
.on('blur','[data-constraints]:not(.once-verified)',function(){
$(this)
.addClass(opt.onceVerifiedClass)
.trigger('validate.form')
})
.on('keyup','[data-constraints].once-verified',function(){
$(this).trigger('validate.form')
})
if($('[data-constraints]',form).length!==0)
$('[data-constraints]',form)
.regula('bind')
.on('show.placeholder',function(){
fieldDesolation($(this))
})
.on('validate.form',fieldValidate)
$('[placeholder]',form).TMPlaceholder()
$('[data-type=submit]',form)
.click(function(){
form.trigger('submit')
return false
})
$('[data-type=reset]',form)
.click(function(){
form.trigger('reset')
return false
})
}
function fieldValidate(el){
var el=$(this)
,result=el.regula('validate')
,isEmpty=false
,isInvalid=false
,isRequired=!!~el.data('constraints').indexOf('@Required')
$.each(result,function(){
if(this.constraintName==='Required')
isEmpty=true
else
isInvalid=true
})
if(!el.hasClass(opt.onceVerifiedClass)&&!isEmpty)
el.addClass(opt.onceVerifiedClass)
if(isEmpty)
el.parents('label').addClass(opt.emptyClass)
if(isInvalid&&!isEmpty&&isRequired)
el.parents('label')
.removeClass(opt.emptyClass)
.removeClass(opt.okClass)
.addClass(opt.invalidClass)
if(isInvalid&&!isRequired&&el.val())
el.parents('label')
.removeClass(opt.emptyClass)
.removeClass(opt.okClass)
.addClass(opt.invalidClass)
if(!result.length)
el.parents('label')
.removeClass(opt.invalidClass)
.removeClass(opt.emptyClass)
.addClass(opt.okClass)
}
function fieldDesolation(el){
el
.removeClass(opt.onceVerifiedClass)
.parents('label')
.removeClass(opt.invalidClass)
.removeClass(opt.emptyClass)
.removeClass(opt.okClass)
}
function getValue(el){
return el.val()||false
}
function formSubmit(){
$('[data-constraints]',form).trigger('validate.form')
if(!$('label.'+opt.invalidClass+',label.'+opt.emptyClass,form).length){
$.ajax({
type:"POST"
,url:opt.mailHandlerURL
,data:{
name:getValue($('label.name input'))
,email:getValue($('label.email input'))
,phone:getValue($('label.phone input'))
,fax:getValue($('label.fax input'))
,state:getValue($('label.state input'))
,message:getValue($('label.message textarea'))
,owner_email:opt.ownerEmail||'[email protected]'
,stripHTML:opt.stripHTML
}
,success: function(e){
form.addClass(opt.successClass)
setTimeout(function(){
form
.removeClass(opt.successClass)
.trigger('reset')
},opt.successShowDelay)
}
})
}
return false
}
function formReset(){
fieldDesolation($('[data-constraints]',form))
}
}
}
})(jQuery)
;(function($){
$.fn.TMPlaceholder=function(opt){
return this.each(function(){
var th=$(this)
,placeholder_text
,placeholder
opt=$.extend({
placeholderClass:'_placeholder'
,placeholderFocusedClass:'focused'
,placeholderHiddenClass:'hidden'
},opt)
init()
function init(){
placeholder_text=th.attr('placeholder')
placeholder=$(document.createElement('span'))
placeholder
.addClass(opt.placeholderClass)
.css({
left:th.prop('offsetLeft')
,top:th.prop('offsetTop')
,width:th.width()
,height:th.outerHeight()
})
.text(placeholder_text)
.appendTo(th.parent())
.click(function(){
th.focus()
return false
})
.on('contextmenu',function(){
th.trigger('hide.placeholder').focus()
})
th
.val('')
.removeAttr('placeholder')
.on('hide.placeholder',function(){
placeholder.addClass(opt.placeholderHiddenClass)
})
.on('show.placeholder',function(){
placeholder.removeClass(opt.placeholderHiddenClass)
})
.on('focus',function(){
placeholder.addClass(opt.placeholderFocusedClass)
})
.on('blur',function(){
var val=th.val()
if(val===''||val===placeholder_text)
th.val('')
,th.trigger('show.placeholder')
placeholder.removeClass(opt.placeholderFocusedClass)
})
.on('keydown',function(e){
if(e.keyCode===32||e.keyCode>46)
th.trigger('hide.placeholder')
})
.on('keyup',function(){
if(th.val()===''){
th.trigger('show.placeholder')
return false
}else{
th.trigger('hide.placeholder')
}
})
.parents('form').on('reset',function(){
th.trigger('show.placeholder')
})
}
})
}
})(jQuery)
//using suggested jQuery practice by passing jQuery into a function
//in order to have $ notation without conflicting with other libraries
//Author: Troy Ingram
//HERE WAS SOME VALIDATION CODE THAT I CANCELLED IN THIS PAGE
regula.custom({
name:'JustLetters'
,validator:function(){
return /^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/.test(this.value)
}
})
regula.custom({
name:'JustNumbers'
,validator:function(){
return /^\+?(\d[\d\-\+\(\) ]{5,}\d$)/.test(this.value)
}
})
$(window).load(function(){
$('#contact-form').TMForm({
ownerEmail:'[email protected]'
})
})
这是 PHP:
<?php
$owner_email = $_POST["owner_email"];
$headers = 'From:' . $_POST["email"] . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'Content-Type: text/plain; charset=UTF-8' . "\r\n";
$subject = 'NEW MESSAGE ' . $_POST["name"];
$messageBody = "";
if($_POST['name']!='nope'){
$messageBody .= '<p>Nome: ' . $_POST["name"] . '</p>' . "\n";
$messageBody .= '<br>' . "\n";
}
if($_POST['email']!='nope'){
$messageBody .= '<p>Email Address: ' . $_POST['email'] . '</p>' . "\n";
$messageBody .= '<br>' . "\n";
}else{
$headers = '';
}
if($_POST['state']!='nope'){
$messageBody .= '<p>State: ' . $_POST['state'] . '</p>' . "\n";
$messageBody .= '<br>' . "\n";
}
if($_POST['phone']!='nope'){
$messageBody .= '<p>Phone Number: ' . $_POST['phone'] . '</p>' . "\n";
$messageBody .= '<br>' . "\n";
}
if($_POST['fax']!='nope'){
$messageBody .= '<p>Fax Number: ' . $_POST['fax'] . '</p>' . "\n";
$messageBody .= '<br>' . "\n";
}
if($_POST['message']!='nope'){
$messageBody .= '<p>Message: ' . $_POST['message'] . '</p>' . "\n";
}
if($_POST["stripHTML"] == 'true'){
$messageBody = strip_tags($messageBody);
}
try{
if(!mail($owner_email, $subject, $messageBody, $headers)){
throw new Exception('mail failed');
}else{
echo 'mail sent';
}
}catch(Exception $e){
echo $e->getMessage() ."\n";
}
?>
对于 1 号表格的 SUBMIT Btn -> 使用
name="formFirst"
对于 2 号表格的 SUBMIT Btn -> 使用
name="formSecond"
并在 PHP 代码中检查
if(isset($_POST['formFirst'])){
//Your code for 1st Form submit.
}
else if (isset($_POST['formSecond'])){
//Your code for 2nd
}
使用 TMForm,您需要为每个表单指定一个唯一的 ID(通过更改 HTML 中的
<form id="form">
行,将第一个表单更改为 <form id="form1">
,将第二个表单更改为 <form id="form2">
)。然后,您需要告诉 TMForm寻找这两个 ID。
为此,请一直转到 TMForm.js 文件的底部并替换
$(window).load(function(){
$('#form').TMForm({
ownerEmail:'#'
})
})
与
$(window).load(function(){
$('#form1').TMForm({
ownerEmail:'#'
})
})
$(window).load(function(){
$('#form2').TMForm({
ownerEmail:'#'
})
})
您没有发布任何 CSS,但如果您使用与我所做的模板类似的模板,您可能会发现现在页面上的内容显示不正确。这是因为 form.css 几乎所有内容都使用 #form,而您只是将该 ID 更改为两个不同的内容。
我发现的最简单的解决方案是查找并用 .tmform 替换 css 文件中 #form 的所有实例
然后,在您的 HTML 中,使您的 ID 看起来像这样:
<form id="form" class="tmform">
<?php
require("conn.php");
// Fetch departments for dropdown
$departments = $conn->query("SELECT * FROM departments");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$salutation = $_POST['salutation'];
$name = $_POST['name'];
$gender = $_POST['gender'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$department_id = $_POST['department'];
$doctor_id = $_POST['doctor'];
if(!preg_match('/^(\+91)?[6-9]\d{9}$/', $phone)) {
echo json_encode(['status' => 'error', 'message' => 'Invalid Phone Number ']);
exit;
}
if (!preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(com|org)$/', $email)) {
echo json_encode(['status' => 'error', 'message' => 'Invalid email. It must end in .com or .org.']);
exit;
}
if (isset($_POST['action']) && $_POST['action'] == 'insert') {
$insert_query = "INSERT INTO patients (salutation, name, gender, phone, email, department_id, doctor_id) VALUES ('$salutation', '$name', '$gender','$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'];
$update_query = "UPDATE patients SET salutation = '$salutation', name = '$name', gender ='$gender', 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 " required>
<option>Mr</option>
<option>Mrs</option>
<option>Ms</option>
<option>Dr</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>
<lable >Gender</lable><br>
<input type="radio" id="gender" name="gender" value="Male" required>
<label for="gender">Male</label>
<input type="radio" id="gender" name="gender" value="Female" required>
<label for="gender">Female</label>
<input type="radio" id="gender" name="gender" value="Others" required>
<label for="gender">Others</label>
</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" required>
<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" required>
<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>Gender</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();
let doctorOptions = '<option value="">Select Doctor</option>';
$('#doctor').html(doctorOptions);
$('#patientForm').find('#edit_id').remove();
loadTable();
}
}
});
});
$(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(http://data.name);
$("#gender[value=" + data.gender + "]").prop('checked', true);
$('#phone').val(data.phone);
$('#email').val(data.email);
$('#department').val(data.department_id).change();
$('#doctor').val(data.doctor_id);
if ($('#edit_id').length === 0) {
$('<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>