我知道在使用AJAX提交表单后如何防止页面重新加载有很多问题和答案,但我无法让我的工作。我已经尝试将按钮设置为type: button
,这样就完全禁用了按钮。当我在表单上尝试onsubmit: return false
时,这不会导致单击按钮。使用jQuery来防止默认也没有成功。我想要的是发送这封电子邮件,PHP从表单中检索数据而不重新加载页面。任何帮助将受到高度赞赏。
<?php include('php/interuni_process.php');?>
<form class="form_pro" action="index.php" method="post" role="form">
<input type="text" class="form" name="E-mail" placeholder="E-mail" value="<?= $email ?>">
<div class="error"><?= $email_error ?></div>
<button name="submit" type="submit" class="action_button"></button>
</form>
$email_error = "";
$email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["E-mail"])) {
$email_error = "E-mail is required";
} else {
$email = test_input($_POST["E-mail"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if ($email_error == '' ){
unset($_POST['submit']);
$to = " Whoever <$email>";
$subject = 'Hello';
$message = "Hello, $firstname!";
if (mail($to, $subject, $message, $headers)){
$email = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
我也试过
$( document ).ready(function() {
$(".form_pro").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "php/interuni_process.php",
data: $(this).serialize(),
success: function(data) {
},
error: function() {
}
});
});
});
答案 0 :(得分:1)
我认为你必须改变逻辑流程才能这样做。 尝试下面的代码,我在我的电脑上测试过。
<script src="jquery-1.11.1.js"></script>
<form id="myData" class="form_pro" method="post" role="form">
<input type="text" class="form" name="E-mail" placeholder="E-mail" value="">
<div class="error"></div>
<button name="submit" type="button" class="action_button" onclick="doSubmit();">OK</button>
</form>
<script>
function doSubmit(){
$.ajax({
url:'interuni_process.php',
data:$("#myData").serialize(),
type:'POST',
success: function (data, textStatus, jqXHR) {
if(data==="SUCCESS"){
$(".error").text("No error occurred");
}else{
$(".error").text("Error occurred: "+ data);
}
}
});
};
</script>
和&#34; interuni_process.php&#34;的示例代码是
<?php
$eMail=$_POST["E-mail"];
if($eMail===""){ //or whatever process condition you want to do
echo "Email cannot be blank";
}else{
echo "SUCCESS";
}
?>
根据您的要求修改业务逻辑
答案 1 :(得分:0)
首先,您从HTML <form>
标记
<form class="form_pro" method="post" role="form">
更改后,按照以下
将return false添加到jquery函数$(document).on('submit','.form_pro',function(){
$.ajax({
url:'interuni_process.php',
type:'POST'
});
return false;
});