AJAX表单不显示成功或错误消息 [英] AJAX form not displaying succes or error message
问题描述
我以前曾问过这个问题,但我仍然没有弄明白。我做了一些改变,但不幸的是我仍然没有得到任何运气。表单本身有效,但当用户尝试发送表单时,它也应该显示错误或成功消息。但不是显示消息,而是发送表单而不显示消息。看看我的代码:
HTML
< form action =method =POST>
< ul class =form-style-1>
< li>
< input type =textid =mail-namename =nameclass =field-dividedmaxlength =15placeholder =Voornaam */>& nbsp;<< ; input type =textid =mail-lastnamename =lastnameclass =field-dividedmaxlength =15placeholder =Achternaam>
< / li>
< li>
< input type =emailid =mail-emailname =emailplaceholder =E-mail *class =field-longmaxlength =40>
< / li>
< li>
< input type =textid =mail-phonename =phoneplaceholder =Telefoonnummerclass =field-longmaxlength =15>
< / li>
< li>
< option disabled value =selected hidden> - Onderwerp-- *< / option>
< option value =Kennismakingsgesprek> Kennismakingsgesprek< / option>
< option value =更多信息>更多信息< / option>
< option value =activiteit>确认活动< / option>
< option value =Vraag / klacht> Vraag / klacht< / option>
< option value =Contact> Overig< / option>
< / select>
< / li>
< li>
< textarea name =informationid =mail-informationplaceholder =Je bericht *class =field-long field-textareamaxlength =2000>< / textarea>
< / li>
< button class =mail-submitid =mail-submittype =submitname =submit>发送电子邮件< / button>
< span class =form-message>< / span>
< / ul>
< / form>
JS (此脚本位于标题中)
$(#mail-submit)。click(function(event){
event.preventDefault(); $ b $ var name = $(#mail-name)。val();
var lastname = $(#mail-lastname).val();
var email = $(# (); val();
var phone = $(#mail-phone)。val();
var subject = $(#mail-subject)。val );
var info = $(#mail-information).val();
$ .post(contact.php,
{
name:name,
姓氏:姓氏,
电子邮件:电子邮件,
电话:电话,
主题:主题,
信息:信息,
提交:是
},
函数(数据){
$(。form-message)。html(data);
}
);
}) ;
PHP (位于PHP文件中)
if(isset($ _ POST ['submit'])){
$ email_to =#;
$ email_subject =#;
$ name = $ _POST ['name'];
$ lastname = $ _POST ['lastname'];
$ email = $ _POST ['email'];
$ phone = $ _POST ['phone'];
$ subject = $ _POST ['subject'];
$ information = $ _POST ['information'];
$ errorEmpty = false;
$ errorEmail = false;
$ b $ if(empty($ name)|| empty($ email)|| empty($ subject)|| empty($ information)){
echo< span class =' form-error'> Voer alle velden in!< / span>;
$ errorEmpty = true;
}
elseif(!filter_var($ email,FILTER_VALIDATE_EMAIL)){
echo< span class ='form-error'> Geef een geldig E-mail!< / span> ;;
$ errorEmail = true;
}
else {
$ formcontent =Naam:$ name \\\
\\\
Achternaam:$ lastname \\\
\\\
Email:$ email \\\
\\\
Telefoon :$ phone \\\
\\\
Onderwerp:$ subject \\\
\\\
Informatie:$ information;
$ mailheader =From:。$ _ POST [email]。\r\\\
;
$ headers =From:。 htmlspecialchars($ _ POST ['name'])。< 。 $ _POST ['email']。 > \r\\\
;
$ headers。=回复:。 $ _POST ['email']。 \r\\\
;
$ headers。=MIME-Version:1.0 \r\\\
;
$ headers。=Content-Type:text / html; charset = ISO-8859-1 \r\\\
;
邮件($ email_to,$ subject,$ formcontent,$ mailheader);
echo< span class ='form-success'>电子邮件已发送!< / span>;
$ / code $ / pre
这是我使用的AJAX脚本: p>
< script src =https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery。 min.js>< /脚本>
解决方案以下是我如何做到的。选择1:一个文件(contact.php),一个表单,没有ajax,没有onclick事件:
<?php
$ emailSent = FALSE;
/ *
* ===================================
*表单提交时的运行操作
* ===================================
* /
if(isset($ _ POST ['submit'])){
/ *
* =============== ===========
*验证发布的值
* ========================= =
* /
if(!isset($ _ POST ['name'])|| empty($ _ POST ['name'])){
$ errors [] ='请提供一个名字。';
$ b $ if(!isset($ _ POST ['email'])|| empty($ _ POST ['email'])){
$ errors [] ='请提供电子邮件。';
} elseif(!filter_var($ _ POST ['email'],FILTER_VALIDATE_EMAIL)){
$ errors [] ='电子邮件无效。
}
/ *
* ============================== ========
*如果所有值都有效,发送电子邮件
* ======================== ==============
* /
if(!isset($ errors)){
$ name = $ _POST ['name'];
$ email = $ _POST ['email'];
//使用发布的值在这里发送电子邮件...
$ emailSent = TRUE;
}
}
?>
<!DOCTYPE html>
< html>
< head>
< meta http-equiv =X-UA-Compatiblecontent =IE = edge,chrome = 1/>
< meta name =viewportcontent =width = device-width,initial-scale = 1,user-scalable = yes/>
< meta charset =UTF-8/>
<! - 上面的3个元标记必须在头部最先出现 - >
< title> Demo< / title>
< script src =https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js>< / script>
< / head>
< body>
< div class =messages>
<?php
if(isset($ errors)){
foreach($ errors as $ error){
?>
< div class =error>
<?php echo $ error; ?>
< / div>
<?php
}
} elseif($ emailSent){
?>
< div class =success>
电子邮件已成功发送。
< / div>
<?php
}
?>
< / div>
< form action =method =POST>
< input type =textid =mail-namename =name/>
< input type =emailid =mail-emailname =email/>
< button class =mail-submitid =mail-submittype =submitname =submit>
发送电子邮件
< / button>
< / form>
< / body>
< / html>
选项2:两个文件,一个ajax,一个onclick事件,根本没有任何形式:
contact.php:
< ;! DOCTYPE html>
< html>
< head>
< meta http-equiv =X-UA-Compatiblecontent =IE = edge,chrome = 1/>
< meta name =viewportcontent =width = device-width,initial-scale = 1,user-scalable = yes/>
< meta charset =UTF-8/>
<! - 上面的3个元标记必须在头部最先出现 - >
< title> Demo< / title>
< script src =https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js>< / script>
< script type =text / javascript>
$(document).ready(function(){
$('#submit')。click(function(event){
$ .ajax({
method:' post',
dataType:'html',
url:'send-email.php',
data:{
'name':$('#name')。 (),
'email':$('#email')。val()
} '.messages').html(response);
},
error:function(jqXHR,textStatus,errorThrown){
var message ='您的请求发生错误,请重试,或联系我们';
$('。messages')。html('< div class =error>'+ message +'< /错误>');
}
});
});
});
< / script>
< / head>
< body>
< div class =messages>< / div>
< div class =contact-form>
< input type =textid =namename =name/>
< input type =emailid =emailname =email/>
< button type =buttonid =submitname =submit>
发送电子邮件
< / button>
< / div>
< / body>
< / html>
send-email.php: $ b
<?php
$ response ='';
$ emailSent = FALSE;
/ *
* ==========================
*验证发布的值
* ==========================
* /
if(!isset($ _ POST [' name'])|| empty($ _ POST ['name'])){
$ errors [] ='请提供一个名字。
$ b $ if(!isset($ _ POST ['email'])|| empty($ _ POST ['email'])){
$ errors [] ='请提供电子邮件。';
} elseif(!filter_var($ _ POST ['email'],FILTER_VALIDATE_EMAIL)){
$ errors [] ='电子邮件无效。
}
/ *
* ============================== ========
*如果所有值都有效,发送电子邮件
* ======================== ==============
* /
if(!isset($ errors)){
$ name = $ _POST ['name'];
$ email = $ _POST ['email'];
//使用发布的值在这里发送电子邮件...
$ emailSent = TRUE;
}
/ *
* ============================== ================================
*分配相应的消息(带有错误或成功类)
* =============================================== ===============
* /
if(isset($ errors)){
foreach($ errors as $ error){
$ response。='< div class =error>'。 $错误。 < / DIV>;
}
} elseif($ emailSent){
$ response。='< div class =success>电子邮件已成功发送< / div>';
}
/ *
* ==================
*打印回复
* ==================
* /
echo $ response;
可选:客户端验证选项1:
您可以在提交之前验证表单,如果至少有一个字段无效(空值,错误的电子邮件地址等),则可以停止提交并显示相应的错误消息:
<?php
$ emailSent = FALSE;
/ *
* ===================================
*表单提交时的运行操作
* ===================================
* /
if(isset($ _ POST ['submit'])){
/ *
* =============== ===========
*验证发布的值
* ========================= =
* /
if(!isset($ _ POST ['name'])|| empty($ _ POST ['name'])){
$ errors [] ='请提供一个名字。';
$ b $ if(!isset($ _ POST ['email'])|| empty($ _ POST ['email'])){
$ errors [] ='请提供电子邮件。';
} elseif(!filter_var($ _ POST ['email'],FILTER_VALIDATE_EMAIL)){
$ errors [] ='电子邮件无效。
}
/ *
* ============================== ========
*如果所有值都有效,发送电子邮件
* ======================== ==============
* /
if(!isset($ errors)){
$ name = $ _POST ['name'];
$ email = $ _POST ['email'];
//使用发布的值在这里发送电子邮件...
$ emailSent = TRUE;
}
}
?>
<!DOCTYPE html>
< html>
< head>
< meta http-equiv =X-UA-Compatiblecontent =IE = edge,chrome = 1/>
< meta name =viewportcontent =width = device-width,initial-scale = 1,user-scalable = yes/>
< meta charset =UTF-8/>
<! - 上面的3个元标记必须在头部最先出现 - >
< title> Demo< / title>
< script src =https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js>< / script>
< script type =text / javascript>
$(document.ready)(function(){
//在所有字段有效前,表单不会提交
$('。contact-form')。submit(function事件){
var messages = [];
var name = $ .trim($('#name')。val());
var email = $。 trim($('#email').val());
//验证用户输入
if(name ===''){
messages.push ('请提供姓名');
}
if(email ===''){
messages.push('请提供电子邮件。');
}
//显示错误信息,如果有的话
if(messages.length> 0){
$('。messages')。html ('');
for(var i = 0; i< messages.length; i ++){
$('。messages')。append('< div class =error>'+ messages [i] +'< / div>');
}
//中止表单提交。
返回false;
}
//继续表单提交。
返回true;
});
});
< / script>
< / head>
< body>
< div class =messages>
<?php
if(isset($ errors)){
foreach($ errors as $ error){
?>
< div class =error>
<?php echo $ error; ?>
< / div>
<?php
}
} elseif($ emailSent){
?>
< div class =success>
电子邮件已成功发送。
< / div>
<?php
}
?>
< / div>
< form class =contact-formaction =method =POST>
< input type =textid =mail-namename =name/>
< input type =emailid =mail-emailname =email/>
< button class =mail-submitid =mail-submittype =submitname =submit>
发送电子邮件
< / button>
< / form>
< / body>
< / html>
当然,对于选项2,您可以轻松实现这种验证,通过在里面包含验证代码onclick处理程序,如果输入无效,则不运行ajax请求。
祝您好运!
I've asked this question before, but I still didn't figure it out. I've made some changes, but I unfortunately still didn't get any luck. The form itself works, but it should also display an error or succes message when the user tries to send the form. But instead of showing the message, it sends the form without showing it. have a look at my code:
HTML
<form action="" method="POST">
<ul class="form-style-1">
<li>
<input type="text" id="mail-name" name="name" class="field-divided" maxlength="15" placeholder="Voornaam *" /> <input type="text" id="mail-lastname" name="lastname" class="field-divided" maxlength="15" placeholder="Achternaam" >
</li>
<li>
<input type="email" id="mail-email" name="email" placeholder="E-mail *" class="field-long" maxlength="40" >
</li>
<li>
<input type ="text" id="mail-phone" name="phone" placeholder="Telefoonnummer" class="field-long" maxlength = "15">
</li>
<li>
<select name="subject" id="mail-subject" class="field-select" >
<option disabled value="" selected hidden >--Onderwerp-- *</option>
<option value="Kennismakingsgesprek">Kennismakingsgesprek</option>
<option value="Meer informatie">Meer informatie</option>
<option value="activiteit">Aanmelding activiteit</option>
<option value="Vraag/klacht">Vraag/klacht</option>
<option value="Contact">Overig</option>
</select>
</li>
<li>
<textarea name="information" id="mail-information" placeholder =" Je bericht *"class="field-long field-textarea" maxlength="2000"></textarea>
</li>
<button class="mail-submit" id="mail-submit" type="submit" name="submit">Send e-mail</button>
<span class="form-message"></span>
</ul>
</form>
JS (this script is located in the header)
$("#mail-submit").click(function(event){
event.preventDefault();
var name = $("#mail-name").val();
var lastname = $("#mail-lastname").val();
var email = $("#mail-email").val();
var phone = $("#mail-phone").val();
var subject = $("#mail-subject").val();
var information = $("#mail-information").val();
$.post("contact.php",
{
name: name,
lastname: lastname,
email: email,
phone: phone,
subject: subject,
information: information,
submit: "yes"
},
function(data){
$(".form-message").html( data );
}
);
});
PHP (Located in a PHP file)
if (isset($_POST['submit'])) {
$email_to = "#";
$email_subject = "#";
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$information = $_POST['information'];
$errorEmpty = false;
$errorEmail = false;
if (empty($name) || empty($email) || empty($subject) || empty($information)) {
echo "<span class='form-error'>Voer alle velden in!</span>";
$errorEmpty = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>Geef een geldig E-mail!</span>";
$errorEmail = true;
}
else {
$formcontent=" Naam: $name \n\n Achternaam: $lastname \n\n Email: $email \n\n Telefoon: $phone \n\n Onderwerp: $subject \n\n Informatie: $information";
$mailheader = "From: ".$_POST["email"]."\r\n";
$headers = "From: ". htmlspecialchars($_POST['name']) ." <" . $_POST['email'] . ">\r\n";
$headers .= "Reply-To: " . $_POST['email'] . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($email_to, $subject, $formcontent, $mailheader);
echo "<span class='form-success'>E-mail has been sent!</span>";
}
}
This is the AJAX script that I use:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
解决方案 Here is how I would do it. I simplified the code for better understanding.
Option 1: One file (contact.php), one form, no ajax, no onclick event:
<?php
$emailSent = FALSE;
/*
* ===================================
* Run operations upon form submission
* ===================================
*/
if (isset($_POST['submit'])) {
/*
* ==========================
* Validate the posted values
* ==========================
*/
if (!isset($_POST['name']) || empty($_POST['name'])) {
$errors[] = 'Please provide a name.';
}
if (!isset($_POST['email']) || empty($_POST['email'])) {
$errors[] = 'Please provide an email.';
} elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Invalid email.';
}
/*
* ======================================
* Send the email if all values are valid
* ======================================
*/
if (!isset($errors)) {
$name = $_POST['name'];
$email = $_POST['email'];
// Send the email here, using the posted values...
$emailSent = TRUE;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="messages">
<?php
if (isset($errors)) {
foreach ($errors as $error) {
?>
<div class="error">
<?php echo $error; ?>
</div>
<?php
}
} elseif ($emailSent) {
?>
<div class="success">
The email was successfully sent.
</div>
<?php
}
?>
</div>
<form action="" method="POST">
<input type="text" id="mail-name" name="name" />
<input type="email" id="mail-email" name="email" />
<button class="mail-submit" id="mail-submit" type="submit" name="submit">
Send e-mail
</button>
</form>
</body>
</html>
Option 2: Two files, an ajax, an onclick event, no form at all:
contact.php:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function (event) {
$.ajax({
method: 'post',
dataType: 'html',
url: 'send-email.php',
data: {
'name': $('#name').val(),
'email': $('#email').val()
},
success: function (response, textStatus, jqXHR) {
$('.messages').html(response);
},
error: function (jqXHR, textStatus, errorThrown) {
var message = 'An error occurred during your request. Please try again, or contact us.';
$('.messages').html('<div class="error">' + message + '</error>');
}
});
});
});
</script>
</head>
<body>
<div class="messages"></div>
<div class="contact-form">
<input type="text" id="name" name="name" />
<input type="email" id="email" name="email" />
<button type="button" id="submit" name="submit">
Send e-mail
</button>
</div>
</body>
</html>
send-email.php:
<?php
$response = '';
$emailSent = FALSE;
/*
* ==========================
* Validate the posted values
* ==========================
*/
if (!isset($_POST['name']) || empty($_POST['name'])) {
$errors[] = 'Please provide a name.';
}
if (!isset($_POST['email']) || empty($_POST['email'])) {
$errors[] = 'Please provide an email.';
} elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Invalid email.';
}
/*
* ======================================
* Send the email if all values are valid
* ======================================
*/
if (!isset($errors)) {
$name = $_POST['name'];
$email = $_POST['email'];
// Send the email here, using the posted values...
$emailSent = TRUE;
}
/*
* ==============================================================
* Assign the corresponding message (with error or success class)
* ==============================================================
*/
if (isset($errors)) {
foreach ($errors as $error) {
$response .= '<div class="error">' . $error . '</div>';
}
} elseif ($emailSent) {
$response .= '<div class="success">The email was successfully sent.</div>';
}
/*
* ==================
* Print the response
* ==================
*/
echo $response;
Optional: Option 1 with client-side validation as well:
You can validate the form before submission and, if at least one field is not valid (empty value, false email address, etc), you can stop the submission and display a corresponding error message instead:
<?php
$emailSent = FALSE;
/*
* ===================================
* Run operations upon form submission
* ===================================
*/
if (isset($_POST['submit'])) {
/*
* ==========================
* Validate the posted values
* ==========================
*/
if (!isset($_POST['name']) || empty($_POST['name'])) {
$errors[] = 'Please provide a name.';
}
if (!isset($_POST['email']) || empty($_POST['email'])) {
$errors[] = 'Please provide an email.';
} elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Invalid email.';
}
/*
* ======================================
* Send the email if all values are valid
* ======================================
*/
if (!isset($errors)) {
$name = $_POST['name'];
$email = $_POST['email'];
// Send the email here, using the posted values...
$emailSent = TRUE;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// The form will not submit before all fields are valid.
$('.contact-form').submit(function (event) {
var messages = [];
var name = $.trim($('#name').val());
var email = $.trim($('#email').val());
// Validate user input.
if (name === '') {
messages.push('Please provide a name.');
}
if (email === '') {
messages.push('Please provide an email.');
}
// Display the error messages, if any.
if (messages.length > 0) {
$('.messages').html('');
for (var i = 0; i < messages.length; i++) {
$('.messages').append('<div class="error">' + messages[i] + '</div>');
}
// Abort the form submission.
return false;
}
// Continue the form submission.
return true;
});
});
</script>
</head>
<body>
<div class="messages">
<?php
if (isset($errors)) {
foreach ($errors as $error) {
?>
<div class="error">
<?php echo $error; ?>
</div>
<?php
}
} elseif ($emailSent) {
?>
<div class="success">
The email was successfully sent.
</div>
<?php
}
?>
</div>
<form class="contact-form" action="" method="POST">
<input type="text" id="mail-name" name="name" />
<input type="email" id="mail-email" name="email" />
<button class="mail-submit" id="mail-submit" type="submit" name="submit">
Send e-mail
</button>
</form>
</body>
</html>
Of course, for option 2, you can achieve such a validation easily, by including the validation code inside the onclick handler, and not running the ajax request if the input is not valid.
Good luck!
这篇关于AJAX表单不显示成功或错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!