我网站上的表格是一个简单的联系表格。当表单发送/失败而不重新加载页面时,我希望表单在同一页面上显示“成功和失败”消息。我知道我应该使用 Ajax 来做到这一点,但我无法让它工作,因为我对它的了解很少。
这是我正在使用的代码。
Html(单页设计):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
<form class="form" id="contactus" action="" method="post" accept-charset="UTF-8">
<label for="nametag">Namn<FONT COLOR="#FF0060">*</FONT></label>
<input name="name" type="text" id="name" value="" />
<label for="emailtag">Email<FONT COLOR="#FF0060">*</FONT></label>
<input name="email" type="text" id="email" value="" />
<label for="phonetag">Telefon</label>
<input name="phone" type="text" id="phone" value="" />
<label for="messagetag">Meddelande<FONT COLOR="#FF0060">*</FONT></label></br>
<textarea name="message" id="message" style="width: 87%; height: 200px;"></textarea>
<label class="placeholder"> </label>
<button class="submit" name="submit">Skicka</button>
</form>
<script>
$(function() {
$('#contactus').submit(function (event) {
event.preventDefault();
event.returnValue = false;
$.ajax({
type: 'POST',
url: 'php/mail.php',
data: $('#contactus').serialize(),
success: function(res) {alert(res);
if (res == 'successful') {
$('#status').html('Sent').slideDown();
}
else {
$('#status').html('Failed').slideDown();
}
},
error: function () {
$('#status').html('Failed').slideDown();
}
});
});
});
</script>
php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$recipient = "info@mydomain.com";
$subject = "Webbkontakt";
$formcontent = "Från: $name <br/> Email: $email <br/> Telefon: $phone <br/> Meddelande: $message";
$headers = "From: " ."CAMAXON<info@mydomain.com>" . "\r\n";
$headers .= "Reply-To: ". "no-reply@mydomain.com" . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=utf-8\r\n";
if(mail($recipient, $subject, $formcontent, $headers))
{
echo "successful";
}
else
{
echo "error";
}
?>