[英]Get a success message on same page after form submit / PHP AJAX
I'm trying to config a contact form based on php/ajax to a website, but I can't manage to add a "success" message after the form is submitted. 我正在尝试将基于php / ajax的联系表单配置为网站,但是提交表单后,我无法添加“成功”消息。 I receive the email correctly if I keep the "action" parameter to the php file inside form tag, but the page gets redirected to the blank php page. 如果将“ action”参数保留在form标记内的php文件中,则可以正确接收电子邮件,但是该页面将重定向到空白的php页面。 However, if I remove the link, the email is not sent. 但是,如果我删除链接,则不会发送电子邮件。
I've tried in the past hours many of the suggestions I found online, but I can't manage to make it work properly. 在过去的几个小时中,我尝试了许多在网上找到的建议,但无法使其正常工作。 Any guesses? 有什么猜想吗?
Thanks 谢谢
HTML HTML
<form id="contact-form" method="POST" action="simple-email-form-v1/form-to-email.php">
<div class="control-group">
<label>Your Name</label>
<input class="fullname" type="text" name="fullname" />
</div>
<div class="control-group">
<label>Email</label>
<input class="email" type="text" name="email" />
</div>
<div class="control-group">
<label>Phone (optional)</label>
<input class="phone" type="text" name="phone" />
</div>
<div class="control-group">
<label>Message</label>
<textarea class="message" name="message"></textarea>
</div>
<div id="errors"></div>
<div class="control-group no-margin">
<input type="submit" name="submit" value="Submit" id="submit" />
</div>
</form>
</div>
PHP PHP
<?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "abcde@gmail.com";//<<=== enter your email address here
//$email_recipients = "mymanager@gmail.com,his.manager@yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Your website
";
$referer = $_SERVER['HTTP_REFERER'];
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "includes/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms@$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
@mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = `enter code here`"From: $email_from \r\n";
@mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if(mail($email_recipients, $_POST["email"], $_POST["message"], $headers)) {
$message = "Success!";
} else {
$message = "Erro!";
}
?>
JS JS
$(document).ready(function () {
$("#contact-form").validate({
rules: {
fullname: {
required: true
},
email: {
required: true,
email: true
},
message: {
required: true,
maxlength: 8000
}
},
messages: { // custom messages
fullname: {
required: "Por favor, insira seu nome"
},
email: {
required: "Por favor, insira seu email"
},
message: {
required: "Por favor, insira sua mensagem",
maxlength: jQuery.format("The maxlength for message is {0} !")
},
},
submitHandler: function(form) {
$form = $(form);
$container = $form.parent();
w = $form.outerWidth();
h = $form.outerHeight();
$form.hide();
$('#msg_submitting', $container).width(w).height(h).fadeIn(1000);
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize(),
success: function (data) {
$("#mail-status").html(data);
},
error:function (){}
});
return false;
}
});
});
Where is the "mail-status" id in html? html中的“邮件状态” ID在哪里? You can replace "mail-status" with "errors". 您可以将“邮件状态”替换为“错误”。
The issue is there is no "mail-status" id in a page, so it is not displaying response on that div. 问题是页面中没有“ mail-status” ID,因此它不在该div上显示响应。
Define "mail-status" on html or just replace "mail-status" with "errors", as your html contains . 在html上定义“ mail-status”,或仅将“ mail-status”替换为“ errors”,因为您的html包含。
Put the <div id="errors"></div>
outside the form element. 将<div id="errors"></div>
放在表单元素之外。 When you are hiding the form the <div id="errors"></div>
also gets hidden hence you cannot see anything. 当您隐藏表单时, <div id="errors"></div>
也会被隐藏,因此您什么也看不到。
<form id="contact-form" method="POST" action="header.php">
<div class="control-group">
<label>Your Name</label>
<input class="fullname" type="text" name="fullname" />
</div>
<div class="control-group">
<label>Email</label>
<input class="email" type="text" name="email" />
</div>
<div class="control-group">
<label>Phone (optional)</label>
<input class="phone" type="text" name="phone" />
</div>
<div class="control-group">
<label>Message</label>
<textarea class="message" name="message"></textarea>
</div>
<div class="control-group no-margin">
<input type="submit" name="submit" value="Submit" id="submit" />
</div>
</form>
<div id="errors"></div>
Also in the php file you need to echo $message;
同样在php文件中,您需要echo $message;
so that it should be available in the ajax data param. 因此它应该在ajax数据参数中可用。
if(mail($email_recipients, $_POST["email"], $_POST["message"], $headers)) {
$message = "Success!";
} else {
$message = "Erro!";
}
echo $message;
First, add this element to the html : 首先,将此元素添加到html中:
<div id="mail-status"></div>
Then add preventDefault()
to the js to prevent the form from submitting : 然后将preventDefault()
添加到js中,以防止表单提交:
<script>
$(document).ready(function () {
$("#contact-form").submit(function(e) {
e.preventDefault(); // added preventDefault()
}).validate({
rules: {
fullname: {
required: true
},
email: {
required: true,
email: true
},
message: {
required: true,
maxlength: 8000
}
},
messages: { // custom messages
fullname: {
required: "Por favor, insira seu nome"
},
email: {
required: "Por favor, insira seu email"
},
message: {
required: "Por favor, insira sua mensagem",
maxlength: jQuery.format("The maxlength for message is {0} !")
},
},
submitHandler: function (form) {
$form = $(form);
$container = $form.parent();
w = $form.outerWidth();
h = $form.outerHeight();
$('#msg_submitting', $container).width(w).height(h).fadeIn(1000);
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize(),
success: function (data) {
$("#mail-status").html(data);
},
error: function () {}
});
$form.hide(); // moved below ajax call
return false;
}
});
});
</script>
Then don't forget to add echo
statement to the php : 然后不要忘记在php中添加echo
语句:
if(mail($email_recipients, $_POST["email"], $_POST["message"], $headers)) {
$message = "Success!";
} else {
$message = "Erro!";
}
echo $message;
Perhaps this might help you: 也许这可以帮助您:
<div id="mail-status"></div>
<form id="contact-form" method="POST" action="simple-email-form-v1/form-to-email.php">
Perhaps the way you handle the submit is causing the page to redirect? 也许您处理提交的方式导致页面重定向?
Change your button type submit
to a button
. 更改按钮类型submit
给button
。 See below, 见下文,
<input type="button" name="submit" value="Submit" id="submit" />
Then, target the button click for the form submission, like this, 然后,将点击按钮定位为表单提交,就像这样,
$(document).ready(function () {
$('#submit').click(function(){
//do you logic here
});
});
When changing the button type to be a button
, you don't need to worry about preventDefault()
for submission, because submission only happens through through Ajax / JS. 将按钮类型更改为button
,无需担心preventDefault()
提交,因为提交仅通过Ajax / JS进行。
Hope this helps. 希望这可以帮助。
Cheers 干杯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.