我一直在通过David Powers的“PHP解决方案”一书学习PHP,该书有一个基本的验证/错误处理和输入清理的联系表单,我想在不刷新页面的情况下使用它。
我正在使用XAMPP在本地测试,并且使用php表单本身运行正常:错误消息正确显示,如果表单成功提交,则会显示一个感谢页面,表单将作为电子邮件发送给我测试电子邮件地址
现在我需要使用AJAX提交和显示错误消息的表单。我已经阅读了很多关于实现这一点的帖子,但是我没有成功实现这一点。我已经尝试了jQuery $ .ajax和$ .post方法 - 如果字段全部填满,则会显示成功消息,但不会发送消息。
我的猜测是javascript和php数组的结构不同,但不知道如何调和它。我甚至不确定php处理脚本正在/发送什么,如果有的话。如何在不刷新页面的情况下提交此表单,但仍然使用php脚本进行服务器端验证?
为了简化,我从我的页面中删除了所有其他内容(并将所有文件放在同一个文件夹中),除了表单:php,html和jQuery / AJAX我无法弄清楚。
希望这是有道理的。我的4个文件:
mySite.js(jQuery / AJAX我遇到麻烦......):
mySite = {
jsFormSubmission : function() {
$("#feedback").submit(function(event){
event.preventDefault();
var errorMsg = "<p class=\"errorBox\">Please fix the item(s) indicated.</p>";
var successMsg = "<p class=\"messageBox\">Thanks for the submission, your message has been sent.</p>";
var myObject = {
name : $("#name").val(),
email : $("#email").val(),
comments : $("#comments").val()
};
var ajaxData = JSON.stringify(myObject);
$.ajax({
type: 'POST',
url: 'form.php',
data: ajaxData,
success: function(data){
$(".formResult").html(successMsg);
},
error: function(http) {
$(".formResult").html(errorMsg);
alert(http.responseText);
}
});
});
}
};
表格(contact.php):
<?php include("form.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src=" mySite.js"></script>
<script type="text/javascript">
$(document).ready(function() {
mySite.jsFormSubmission();
});
</script>
</head>
<body>
<div id="contact">
<p class="formResult"></p>
<?php $errorForm = (($_POST && $suspect) || ($_POST && isset($errors['mailfail'])));
$errorTag = $missing || $errors;
if ($errorForm || $errorTag) { ?>
<p class="errorBox">
<?php } ?>
<?php if ($errorForm) { ?>
Sorry, your message could not be sent. Please try again later.
<?php } elseif ($errorTag) { ?>
Please fix the item(s) indicated.
<?php } ?>
<?php if ($errorForm || $errorTag) { ?>
</p>
<?php } ?>
<form id="feedback" method="post" action="">
<div class="tag">
<label id="lblName" for="name">Name:
<?php if ($missing && in_array('name', $missing)) { ?>
<span style="color:red; font-weight:bold;">Please enter your name</span>
<?php } ?>
</label>
<input name="name" id="name" type="text" class="formbox"
<?php if ($missing || $errors) {
echo 'value="' . htmlentities($name, ENT_COMPAT, 'UTF-8') . '"';
} ?>>
</div>
<div class="tag">
<label id="lblEmail" for="email">Email:
<?php if ($missing && in_array('email', $missing)) { ?>
<span style="color:red; font-weight:bold;">Please enter your email address</span>
<?php } elseif (isset($errors['email'])) { ?>
<span style="color:red; font-weight:bold;">Invalid email address</span>
<?php } ?>
</label>
<input name="email" id="email" type="text" class="formbox"
<?php if ($missing || $errors) {
echo 'value="' . htmlentities($email, ENT_COMPAT, 'UTF-8') . '"';
} ?>>
</div>
<div class="tag">
<label id="lblComments" for="comments">Comments:
<?php if ($missing && in_array('comments', $missing)) { ?>
<span style="color:red; font-weight:bold;">Please enter your message</span>
<?php } ?>
</label>
<textarea name="comments" id="comments" cols="60" rows="8"><?php
if ($missing || $errors) {
echo htmlentities($comments, ENT_COMPAT, 'UTF-8');
} ?></textarea>
</div>
<p>
<input name="send" id="send" type="submit" value="Send message">
</p>
</form>
</div>
</body>
</html>
form.php(包含在contact.php的顶部):
<?php
$name = '';
$email = '';
$comments = '';
$required = '';
$errors = array();
$missing = array();
// check if the form has been submitted
if (isset($_POST['send'])) {
//email processing script
$to = 'johntest2@localhost';
$subject = 'Website contact form';
//list expected fields
$expected = array('name', 'email', 'comments');
// set required fields
$required = array('name', 'email', 'comments');
$headers = "From: Website Contact Test<johntest1@localhost>\r\n";
$headers .= 'Content-Type: text/plain; charset=utf-8';
require('processmail.php');
if ($mailSent) {
header("Location: thankYou.php#main");
$messageConfirm = true;
exit;
}
}
?>
processmail.php(验证脚本 - 包含在form.php中):
<?php
$suspect = false;
$pattern = '/Content-Type:|Bcc:|Cc:/i';
// function to check for suspect phrases
function isSuspect($val, $pattern, &$suspect) {
if (is_array($val)) {
foreach ($val as $item) {
isSuspect($item, $pattern, $suspect);
}
} else {
if (preg_match($pattern, $val)) {
$suspect = true;
}
}
}
isSuspect($_POST, $pattern, $suspect);
if (!$suspect) {
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value);
if (empty($temp) && in_array($key, $required)) {
$missing[] = $key;
} elseif (in_array($key, $expected)) {
${$key} = $temp;
}
}
}
// validate the user's email
if (!$suspect && !empty($email)) {
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "\r\nReply-To: $validemail";
} else {
$errors['email'] = true;
}
}
$mailSent = false;
if (!$suspect && !$missing && !$errors) {
// initialize the $message variable
$message = '';
foreach($expected as $item) {
if (isset(${$item}) && !empty(${$item})) {
$val = ${$item};
} else {
$val = 'Not selected';
}
if (is_array($val)) {
$val = implode(', ', $val);
}
$item = str_replace(array('_', '-'), ' ', $item);
$message .= ucfirst($item).": $val\r\n\r\n";
}
$message = wordwrap($message, 70);
$mailSent = mail($to, $subject, $message, $headers);
if (!$mailSent) {
$errors['mailfail'] = true;
}
}
答案 0 :(得分:1)
您可以通过几种方式从PHP端获取错误。你可以抛出一个我不推荐的例外,或使用标题:
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
在您的AJAX调用中,使用jQuery错误回调:
$.ajax({
url: //url,
data: //data,
success: function (data) { //show success },
error: function () { //display code here }
});
您还可以从PHP端返回错误消息正文中的错误,并在错误回调中从正文中删除该错误。
PHP:
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
echo 'Your error message';
JavaScript的:
error: function(http) {
// show http.responseText;
}
此外,对于表单提交,请将数据打包到对象中,然后对其进行序列化。所以:
var myObject = {
property1 : 'string',
property2 : [ 'array' ]
};
var ajaxData = JSON.stringify(myObject);