我一直在通過David Powers的書「PHP Solutions」學習PHP,它有一個聯繫表單,包含基本驗證/錯誤處理和輸入消毒,我希望在不刷新的情況下使用這一頁。AJAX與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>
形式.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 = '[email protected]';
$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<[email protected]>\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;
}
}
'data:'$(「#feedback」)。serializeArray();','不正確。它會將JS代碼作爲字符串提交,而不是序列化調用的輸出 - 從未將代碼視爲字符串以外的任何其他代碼。你在這條線上面還有一個流浪的'''''''''''''''''''' – 2013-02-12 15:34:38
嗯,是的,我不小心刪除了'當我發佈這個。感謝您指出了這一點。 – JMurky 2013-02-12 18:45:46
我看到你對數據的觀點:''是一個字符串。我替換了我用來嘗試縮短我的代碼張貼的變量。如果我刪除撇號和分號,所以它讀取數據:$(「#feedback」)。serializeArray(),我仍然無法使用ajax提交。 – JMurky 2013-02-13 06:47:52