我见过几个类似的问题,但找不到任何相关的问题。
我有一个基本表单捕获用户电子邮件我想要的是当表单提交时它不会加载空白页面,而只是再次重定向回空表单。
<?php
if ($thanks === false) {
echo form::open('', array('id'=>'footer_email'));
echo '<div id="footer_box">';
echo '<div class="footer_box_left">';
echo form::input('form[email]', $val, array('class'=>'required', 'id'=>'email', 'placeholder'=>'Enter email address'));
echo '</div>';
echo form::submit('btnSubmit', 'Sign Up', array('id'=>'btnSubmit', 'class'=>'footer_box_submit'));
echo '</div>';
echo form::close();
}
?>
$(document).ready(function () {
var validator = $("#footer_email").validate({
errorLabelContainer: $("#footer_email div.error"),
meta: "validate",
invalidHandler: function (form, validator) {
alert("Please enter your email address first.");
},
submitHandler: function (form) { // on submit
if ($(form).valid())
form.submit();
alert("Thank you for sharing your email address. \nKarina");
return false;
}
});
});
任何人都可以告诉我哪里出错了/我会更好地使用ajax来实现这个目标吗?
答案 0 :(得分:1)
你可以这样做:
<?php
if ($thanks === false) {
echo form::open('', array('id'=>'footer_email'));
echo '<div id="footer_box">';
echo '<div class="footer_box_left">';
echo form::input('form[email]', $val, array('class'=>'required', 'id'=>'email', 'placeholder'=>'Enter email address'));
echo '</div>';
echo form::submit('btnSubmit', 'Sign Up', array('id'=>'btnSubmit', 'class'=>'footer_box_submit'));
echo '</div>';
echo form::close();
} else {
echo '<script>alert("Thank you for sharing your email address. \nKarina");</script>';
echo form::open('', array('id'=>'footer_email'));
echo '<div id="footer_box">';
echo '<div class="footer_box_left">';
echo form::input('form[email]', $val, array('class'=>'required', 'id'=>'email', 'placeholder'=>'Enter email address'));
echo '</div>';
echo form::submit('btnSubmit', 'Sign Up', array('id'=>'btnSubmit', 'class'=>'footer_box_submit'));
echo '</div>';
echo form::close();
}
?>
答案 1 :(得分:0)
因为您正在使用
form.submit();
这会使通常的表单提交,就像您点击“发送”按钮一样。你想要做的是发送通过Ajax序列化的表单,
var formData = $(form).serialize();
$.post('[HERE YOUR SUBMIT TARGET URL]', formData, function (success){
///Redirect to empty form, or clear actual form
});
答案 2 :(得分:0)
使用Ajax保持快速且无需多次刷新
$(document).ready(function () {
var validator = $("#footer_email").validate({
errorLabelContainer: $("#footer_email div.error"),
meta: "validate",
invalidHandler: function (form, validator) {
alert("Please enter your email address first.");
},
submitHandler: function (form) { // on submit
if ($(form).valid()) {
$.ajax({
type: "POST",
url: url,
data: $(form).serialize()
}).done(function (data) {
alert("Thank you for sharing your email address. \nKarina");
$(form).reset();
}).fail(function () {
alert("Sorry Try again. \nKarina");
});
}
return false;
}
});
});