Javascript 成功返回到原始页面。Boostramp+;PHPMailer
我试图做到这一点,当用户输入我的联系人表单而不是重定向到“mail.php”文件时,他们只会看到一条消息,表明该消息已在同一页面上成功发送。我已经尝试了很多关于JS的教程,但我仍然不知道如何做到这一点 PHP邮件程序和Html工作,它只是javascript,旨在向用户显示不工作的成功或失败消息 我最初尝试将JS放在另一个文件中,然后在jQuery下面的页面底部将其作为另一个脚本调用,但这不起作用,我可能会将其移回自己的文件 我的HTML当前看起来像Javascript 成功返回到原始页面。Boostramp+;PHPMailer,javascript,php,jquery,Javascript,Php,Jquery,我试图做到这一点,当用户输入我的联系人表单而不是重定向到“mail.php”文件时,他们只会看到一条消息,表明该消息已在同一页面上成功发送。我已经尝试了很多关于JS的教程,但我仍然不知道如何做到这一点 PHP邮件程序和Html工作,它只是javascript,旨在向用户显示不工作的成功或失败消息 我最初尝试将JS放在另一个文件中,然后在jQuery下面的页面底部将其作为另一个脚本调用,但这不起作用,我可能会将其移回自己的文件 我的HTML当前看起来像 <div class="fo
<div class="form-container">
<form id="contact-form" method="post" action="mail.php" name="contact-form" role="form" >
<div class="row">
<div class="col-md-6" style="padding-right: 4px;">
<input type="text" name="first_name" id="name" placeholder="Name" required />
</div>
<div class="col-md-6" style="padding-left: 4px;">
<input type="email" name="email" id="email" placeholder="Email" oninvalid="this.setCustomValidity('Please enter valid email address.')" onchange="this.setCustomValidity('')" required />
</div>
</div>
<input type="text" name="subject" id="subject" placeholder="Why are you contacting me?" required />
<textarea name="message" id="message" cols="30" rows="10" placeholder="Tell me more about your propersition?" required></textarea>
<input type="submit" id="submit" name="submit" value="submit">
<label class="checkbox-label">
<input type="checkbox" id="tos" name="tos" oninvalid="this.setCustomValidity('Please read the Terms of Service.')" onchange="this.setCustomValidity('')" required>
<span class="checkbox-custom rectangular"></span>
</label>
<label for="tos">I agree to the <a href="tos.php">Terms of Service</a></label>
</form>
</div>
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
require 'vendor/autoload.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'mail.edbrook.site'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'info@edbrook.site'; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('info@edbrook.site', 'Web Contact');
$mail->addAddress('ed@edbrook.site', 'Admin - Edbrook.site'); // Add a recipient
// message that will be displayed when everything is OK :)
$okMessage = 'Thank you for your message. We will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error. Please try again later!';
//Content
$mail->isHTML(true); // Set to HTML
$mail->Subject = 'Contact Form Message';
$mail->Body = "Full Name: ".htmlspecialchars($_POST['first_name'])."<br />Email Address: ".htmlspecialchars($_POST['email'])."<br /><br />";
$mail->send();
$responseArray = array('type' => 'success', 'message' => $okMessage);
} catch (Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
} catch (Error $e) {
// should log the fatal
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
// if the validator good
if (!e.isDefaultPrevented()) {
var url = "mail.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// apply success/danger
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable" role="alert"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('The ajax request failed:' + errorThrown);
}
});
return false;
}
})
});
我同意这个建议
我的PHP邮件程序文件(Mail.PHP)当前看起来像
<div class="form-container">
<form id="contact-form" method="post" action="mail.php" name="contact-form" role="form" >
<div class="row">
<div class="col-md-6" style="padding-right: 4px;">
<input type="text" name="first_name" id="name" placeholder="Name" required />
</div>
<div class="col-md-6" style="padding-left: 4px;">
<input type="email" name="email" id="email" placeholder="Email" oninvalid="this.setCustomValidity('Please enter valid email address.')" onchange="this.setCustomValidity('')" required />
</div>
</div>
<input type="text" name="subject" id="subject" placeholder="Why are you contacting me?" required />
<textarea name="message" id="message" cols="30" rows="10" placeholder="Tell me more about your propersition?" required></textarea>
<input type="submit" id="submit" name="submit" value="submit">
<label class="checkbox-label">
<input type="checkbox" id="tos" name="tos" oninvalid="this.setCustomValidity('Please read the Terms of Service.')" onchange="this.setCustomValidity('')" required>
<span class="checkbox-custom rectangular"></span>
</label>
<label for="tos">I agree to the <a href="tos.php">Terms of Service</a></label>
</form>
</div>
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
require 'vendor/autoload.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'mail.edbrook.site'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'info@edbrook.site'; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('info@edbrook.site', 'Web Contact');
$mail->addAddress('ed@edbrook.site', 'Admin - Edbrook.site'); // Add a recipient
// message that will be displayed when everything is OK :)
$okMessage = 'Thank you for your message. We will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error. Please try again later!';
//Content
$mail->isHTML(true); // Set to HTML
$mail->Subject = 'Contact Form Message';
$mail->Body = "Full Name: ".htmlspecialchars($_POST['first_name'])."<br />Email Address: ".htmlspecialchars($_POST['email'])."<br /><br />";
$mail->send();
$responseArray = array('type' => 'success', 'message' => $okMessage);
} catch (Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
} catch (Error $e) {
// should log the fatal
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
// if the validator good
if (!e.isDefaultPrevented()) {
var url = "mail.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// apply success/danger
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable" role="alert"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('The ajax request failed:' + errorThrown);
}
});
return false;
}
})
});
有几件事你需要改变
如果不想重定向到mail.php,请将其从表单的操作
属性中删除。由于您是通过JavaScript注入成功/失败消息,请添加onsubmit=“return false;”
以防止页面刷新
<form id="contact-form" method="post" action="" name="contact-form" role="form" onsubmit="return false;">
我在HTML中看不到类名为messages
的div
在内部添加e.preventDefault()
$(“#联系方式”)。关于('submit',函数(e){
e、 preventDefault();//此处
在
标签内添加新的
:
这是您可以完全使用的代码。您的ajax
和HTML
您需要在$.ajax
请求中设置dataType:json
,因为从PHP文件返回的响应是json格式的
您的HTML不包含任何将显示成功或错误消息的.messages
div
此外,对于表单
提交,您需要使用this=>$(“#联系表单”).submit(函数(e){})
,并使用e.preventDefault()
确保页面不会在表单
提交中重新加载
我假设您的PHPMailer
工作正常,并且已经在发送电子邮件。您只需要使用以下HTML和jQuery
代码,这样成功消息就会显示在contant.php
页面上,而不是另一页面上
我已经在localHost
上测试了我的代码,并且工作正常,并且发送了电子邮件
,其中包含正确的表单信息数据
jQuery
$(function() {
$('#contact-form').submit(function(e) {
e.preventDefault()
var url = "mail.php";
//POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
// data = JSON object that contact.php returns
// apply success/danger
var messageAlert = 'alert-' + data.type;
var messageText = data.message
// Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable" role="alert"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>'
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('.form-container').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('The ajax request failed:' + errorThrown);
}
});
return false;
})
});
$(函数(){
$(“#联系方式”)。提交(功能(e){
e、 预防默认值()
var url=“mail.php”;
//在脚本URL的后台发布值
$.ajax({
类型:“POST”,
url:url,
数据类型:“json”,
数据:$(this).serialize(),
成功:功能(数据){
//data=contact.php返回的JSON对象
//应用成功/危险
var messageAlert='alert-'+data.type;
var messageText=data.message
//引导警报框HTML
var alertBox='×;'+messageText+''
//如果我们有messageAlert和messageText
if(messageAlert&&messageText){
//将警报注入表单中的.messages div
$('.form container').find('.messages').html(alertBox);
//清空表格
$(“#联系方式”)[0]。重置();
}
},
错误:函数(jqXHR、textStatus、errorshown){
console.error('ajax请求失败:'+errorshown);
}
});
返回false;
})
});
HTML
<div class="form-container">
<form id="contact-form" method="post" action="mail.php" name="contact-form" role="form">
<div class="row">
<div class="col-md-6" style="padding-right: 4px;">
<input type="text" name="first_name" id="name" placeholder="Name" required />
</div>
<div class="col-md-6" style="padding-left: 4px;">
<input type="email" name="email" id="email" placeholder="Email" oninvalid="this.setCustomValidity('Please enter valid email address.')" onchange="this.setCustomValidity('')" required />
</div>
</div>
<input type="text" name="subject" id="subject" placeholder="Why are you contacting me?" required />
<textarea name="message" id="message" cols="30" rows="10" placeholder="Tell me more about your propersition?" required></textarea>
<input type="submit" id="submit" name="submit" value="submit">
<label class="checkbox-label">
<input type="checkbox" id="tos" name="tos" oninvalid="this.setCustomValidity('Please read the Terms of Service.')" onchange="this.setCustomValidity('')" required>
<span class="checkbox-custom rectangular"></span>
</label>
<label for="tos">I agree to the <a href="tos.php">Terms of Service</a></label>
</form>
<div class="messages"></div>
</div>
我同意这个建议
这仍然会将我重定向到Mail.php页面。请尝试使用e.stopImmediatePropagation()
而不是现在,当输入数据并单击“提交”时,绝对不会发生任何事情,表单也不会被提交。您不需要提交表单。首先,在浏览器控制台中检查您的AJAX
是否正在启动。其次,您是否添加了一个类为消息的div
?您不需要提交表单是什么意思e是他们必须点击的提交按钮?Ajaxz没有启动。我收到了一个关于验证的错误,但我删除了它,然后我在ajax上面输入了一个console.log,以查看js是否正在运行,但ajax没有。