[英]AJAX form submission, solely to prevent page refresh and nothing else
我建立了一個簡單的HTML / PHP電子郵件注冊表單,該表單顯示在我的網站的頁腳區域中。 只有兩個字段: email和country 。
該表格非常適合我的目的。 數據收集,驗證,清理,錯誤處理,清除字段,成功通知等-一切順利!
我的最后一步是實現AJAX以防止頁面刷新。 這是AJAX所需的全部。
我發現該站點上的所有教程,文章和相關問題的答案都提供了包含已使用PHP處理過的功能的代碼。
我已經達到了AJAX提交的要求,可以正常工作。 頁面沒有刷新,用戶輸入已插入數據庫,並且我收到確認電子郵件。
我希望獲得一些指導(或指向教程的鏈接),它們可以幫助我實現PHP錯誤邏輯並回顯PHP成功/錯誤消息。
HTML
<form action="process_footer_form/" method="post" id="footer-form">
<ul>
<li>
<input type="email" name="email" id="email"
value="<?php if (isset($email)) {echo $email;} ?>">
</li>
<li>
<input type="text" name="country" id="country"
value="<?php if (isset($country)) {echo $country;} ?>">
</li>
<li>
<input type="submit" name="submit" id="submit">
</li>
</ul>
<?php if (isset($success_message)) {echo $success_message;} ?>
<?php if (isset($error_message)) {echo $error_message;} ?>
</form>
JQuery的
$(function() {
// identify form
var form = $('#footer-form');
// create event listener
$(form).submit(function(event) {
// disable html submit button
event.preventDefault();
// serialize form data
var formData = $(form).serialize();
// submit form using AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// 1. echo PHP success message
// 2. fire PHP clear fields command
})
.fail(function(data) {
// 3. execute PHP error logic here
// 4. echo PHP error messages
});
});
});
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Load PHPMailer
require 'PHPMailer/PHPMailerAutoload.php';
// Create PHPMailer session
$mail = new PHPMailer;
$mail->CharSet = "UTF-8";
// SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.xxxxxxxxxx.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->Username = 'xxxxxxxxxxxxxxxxxx';
$mail->Password = 'xxxxxxxxxxxxxxxxxx';
$mail->setFrom('xxxxxxxxxxxxxxxxxx' , 'xxxxxxxxxxxxxxxxxx');
$mail->addAddress('xxxxxxxxxxxxxxxxxx');
$mail->isHTML(true);
// Sanitize & Validate Input
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$country = trim(filter_input(INPUT_POST, 'country', FILTER_SANITIZE_SPECIAL_CHARS));
// set connection to mysql server
$connection = mysql_connect("localhost","xxxxxxxxxxxxxxxxxx","xxxxxxxxxxxxxxxxxx");
// connect to database
mysql_select_db("xxxxxxxxxxxxxxxxxx", $connection);
// insert user input to table
$sql = "INSERT INTO email_subscribers (email,country) VALUES ('$email','$country')";
if (!$connection) {
$error_message = <<<ERROR
<div>ERROR. Form not sent. Please try again or <a href="contact/">contact us</a>.</div>
ERROR;
// Send error notice to host
$mail->Subject = 'Website Error - Footer Form';
$mail->Body = ("Error Notice: A site user is having trouble on the footer form.");
$mail->send();
} else {
// run query
mysql_query($sql, $connection);
$success_message = <<<CONFIRMATION
<div>Subscription complete. Thank you!</div>
CONFIRMATION;
mysql_close($connection);
// Send confirmation notice to host.
$message = <<<HTML
<span>E-mail: {$email}</span><br>
<span>Country: {$country}</span>
HTML;
$mail->Subject = 'New E-mail Subscriber - Footer Form';
$mail->Body = $message;
$mail->send();
unset($email, $country);
}
} else {
header('Location: http://www.mywebsite.com/');
exit;
}
?>
您可以嘗試使用FormData對象簡化生活。 然后您的代碼可能看起來像這樣。 我已經測試過了。
<form method="POST" id="subscription-form" enctype="multipart/form-data">
<input type="email" name="email" id="email" value="gulliver@tinyletter.com">
<input type="text" name="country" id="country" value="Lilliput">
<input type="button" value="submit" id="form-submit">
</form>
在此之下,您可以在div中顯示消息:
<div id="messages"></div>
然后,您的jquery / javascript將如下所示:
<script>
(function(){
$("#form-submit").on("click", function(){ submitForm();});
})();
function submitForm(){
var form = document.getElementById("subscription-form");
var fd = new FormData(form);
$.ajax({
url: './PHPscript.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
$("#messages").html(data);
}
});
}
</script>
關於讓PHP“處理消息”,我認為您缺少有關AJAX的知識。
在您最初的PHP頁面中,您將加載PHP生成的html,然后完成PHPs部分。 進行AJAX調用時,您正在要求服務器執行其他PHP腳本,然后將該腳本的輸出返回給javascript。
那時,您需要將PHP生成的任何消息放回當前頁面,該消息尚未並且不會重新加載。 這首先是使用AJAX的目的。 這就是“郵件” div的目的。
為了完全理解這一點,請創建一個非常簡單的PHPscript.php文件,如下所示並嘗試一下:
<?php
print $_POST['email'] . ' ' . $_POST['country'];
?>
您將在該消息div中的當前頁面中看到返回的值。
第一個請求,例如www.mysite.com/something.php
將運行PHP並將結果轉儲到頁面中。 Ajax不能這樣工作。 您將request
到PHP文件,然后發送response
,然后您可以檢查該response
並執行某些操作。
如果ajax響應像初始加載一樣將其內容轉儲到頁面中,則會發生混亂。
嘗試這樣的事情:
$.ajax({
url: url,
type: type,
data: data
}).done(function (response) {
console.log(response);
});
然后在控制台中添加一個外觀,看看您從PHP腳本中獲得了什么好處。 然后構建該.done
回調以處理您的請求結果並確定要執行的操作。
好的,首先, var that = this
當您丟失上下文時, var that = this
是一個把戲,但是在不使用它的地方,您可能會丟失它..所以就算了:)
然后,您的find().each()
,這是獲取值的好方法,但是jquery提供了一個$( this ).serializeArray()
(它確實正是您想要的方法)
另外,您使用ajax發送數據,但是沒有回調。 一旦一切正常,您的ajax調用至少需要有一個函數可以調用。 這是通過done()
最后,在大多數情況下,返回false
會取消該事件,但是您最好使用preventDefault()
因為它會禁用默認行為,但仍會傳播事件(對於其他處理程序)。
總結一下:
$('form.ajax').submit( function(event) {
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serializeArray()
}).done(function(data) {
alert("Ajax call successful");
console.log("Server answer:" + data);
});
event.preventDefault();
});
編輯:Nvm我的第一句話,我最近了解您的that = this
東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.