我试图让我的 Ajax 代码在返回同一页面之前与我的 PHP 文件对话。
我希望填写我的表单,一旦发送,它就会与我的 AJAX 代码对话,因此在向最终用户返回成功或失败消息之前,它会与 PHP 文件对话。
Ajax 代码如下:
$(document).ready(function(){
$(function() {
$(".submit").click(function() {
// validate and process form here
var fname = $("#fname").val() ;
var lname = $("#lname").val();
var aemail = $("#aemail").val() ;
var year = $("#year").val();
var club = $("#club").val() ;
var position = $("#position").val();
var dataString = 'name='+ name + '&fname=' + fname + '&lname=' + lname + '&aemail=' + aemail + '&year=' + year + '&club=' + club + '&position=' + position;
$.ajax({
type: "POST",
url: "acad_process.php",
data: dataString,
success: function(){
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>Thank you. We will be in touch soon.</p>")
};
return false;
error: function(){
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Failed!</h2>")
.append("<p>Sorry, your form returned an error! Please try again.</p>")
.hide()
.fadeIn(1500, function() {
});
};
return false;
});
});
});
});
</script>
任何帮助将非常感激。因为我是 AJAX 的新手。谢谢
问题似乎是 PHP,因为在进一步调查中,我在 PHP 页面上收到错误 500 omn,并且没有任何内容返回到我的页面。PHP代码是:
<?php
$email_to = "example@domain.co.uk";
if (!empty($_POST))
{
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$email_from = $_POST["aemail"];
$year = $_POST ["year"];
$club = $_POST ["club"];
$position = $_POST ["position"];
$email_subject = "Enquiry";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers = "From: $email_from . \n";
$headers = "Reply-To: $email_from . \n";
$message = "<p> You have received a message!</p>";
$message .= "<p><strong>First Name:</strong>" . $fname . "</p>";
$message .= "<p><strong>Surname:</strong>" . $lname . "</p>";
$message .= "<p><strong>School Year:</strong> " . $year . "</p>";
$message .= "<p><strong>E-Mail:</strong>" . $aemail ."</p>";
$message .= "<p><strong>Club:</strong> " . $club . "</p>";
$message .= "<p><strong>Position:</strong>" . $position . "</p>";
ini_set("sendmail_from",$email_from);
mail($email_to, $email_subject, $message, $headers, '-f'.$email_from);
}
?>