我想創建電子郵件聯繫表單而不刷新頁面。所以我使用jquery。現在提交表單後,我想發送成功或錯誤消息給用戶。這裏是我的代碼:無法在提交表單後顯示成功或錯誤消息,而無需刷新頁面
的index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5 Contact Form</title>
<link rel="stylesheet" media="screen" href="styles.css" >
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$('#mycontactform').submit(function(e){
e.preventDefault();
$.post("contact.php", $(this).serialize(), function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
});
});
</script>
</head>
<body>
<form id="mycontactform" class="contact_form" action="" method="post" name="contact_form">
<ul>
<li>
<h2>Contact Us</h2>
<span class="required_notification">* Denotes Required Field</span>
</li>
<li>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="John Doe" required />
</li>
<li>
<label for="email">Email:</label>
<input type="email" name="email" id="email" placeholder="[email protected]" required />
<span class="form_hint">Proper format "[email protected]"</span>
</li>
<li>
<label for="message">Message:</label>
<textarea name="message" id="message" cols="40" rows="6" required ></textarea>
</li>
<li>
<button class="submit" id="submit" style="cursor:pointer" type="submit">Submit Form</button>
<div id="success" style="color:red;"></div>
</li>
</ul>
</form>
</body>
</html>
contact.php
<?php
$field_name = $_POST['name'];
$field_email = $_POST['email'];
$field_message = $_POST['message'];
$mail_to = '[email protected]';
$subject = 'Message from a site visitor '.$field_name;
$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Message: '.$field_message;
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) {
echo "Your email was sent!";
} else {
echo "Your email was not sent!";
}
?>
現在提交表單,如果郵件成功發送後,我想,如果要顯示的PHP語句如果郵件沒有發送,我會發送其他語句來執行。但提交表單後,我沒有收到成功或錯誤消息,也沒有收到任何郵件?我哪裏錯了?我的jQuery代碼是否正確提交表單而不刷新頁面?有人幫我
檢查在瀏覽器中的錯誤的JavaScript控制檯和網絡選項卡。 –
您將需要使用JavaScript來提交它,閱讀消息並將其顯示給用戶。嘗試搜索AJAX – Anigel
它看起來像javascript行'return false;'和下面的兩個'});'不應該在那裏,並可能導致腳本錯誤。 –