[英]Disable e.preventDefault() if successful post validation
以下是我要如何發生的事情:
1. User answers the form, clicks submit
2. The data will be evaluated by the CodeIgniter `validate_new_account()`
a. If there are errors, prevent submission so that the dynamically added fields will not disappear
b. If successful / no error validation, proceed to the **else** part of `validate_new_account()` to `$this->view_preview_form( $this->get_post_data() );`
我有一個表單,並將其提交給我的控制器的validate_new_account()
函數:
function validate_new_account()
{
// validations here
if ( $this->form_validation->run() == FALSE ) {
// JSON-encoded validations
$errors = json_encode( $this->form_validation->error_array() );
echo $errors;
} else {
// next step
$this->view_preview_form( $this->get_post_data() );
}
}
我使用jQuery Form Plugin與控制器進行交互。
var options = {
url: "<?php echo site_url('new_account/validate_new_account'); ?>",
type: 'POST',
dataType: 'json',
success: function(data) {
if (data.length === 0) {
alert('Form successfully submitted!');
} else {
// echo validation errors from CodeIgniter
alert("Some fields weren't answered successfully. Please answer them.");
$.each(data, function(key, value){
var container = '<div class="error">'+value+'</div>';
$('.form-element input[name="'+key+'"]').after(container);
});
}
}
};
$('#main-submit').click(function(e) {
$('#main-form').valid();
$('#main-form').ajaxSubmit(options);
e.preventDefault();
});
沒有我的ajax函數,上面的代碼會完美地工作,但是我已經動態添加了一些元素,這些元素需要ajax來處理所有驗證,否則這些元素將消失(錯誤的UX)。
因此,如果我啟用並使用了我的ajax函數,那么如果現在所有驗證均正確,那么 CodeIgniter的驗證錯誤就會打印出我想要的方式(通過ajax的成功部分), 但是該窗體不會轉到$this->view_preview_form( $this->get_post_data() );
。
為什么會這樣呢? 我一直在尋找類似的問題,但不幸的是,沒有一個與我的情況類似。
如果表單發送成功,如何通過e.preventDefault()
?
對於所有幫助我解決此問題的人,可能是評論還是答案,非常感謝。 我一直在尋找這個解決方案(CodeIgniter驗證+ jQuery驗證+ AJAX提交+無縫文件上傳)兩個月了,現在我終於可以呼吸了。 我永遠不會忘記您的所有幫助。 您永遠不會知道這對我有多重要。
簡單:
<script>
$('form').on('submit', function(e) {
// do your AJAX validation here
var url = $(this).attr('action');
var params = $(this).serialize();
$.post(url, params, function(response) {
if (response.errors.length > 0) {
e.preventDefault();
}
});
});
</script>
如果返回的錯誤不止一個,這將阻止表單提交。 否則,事件將正常進行並傳播。
我認為在驗證之后,您想阻止表單提交,以防止重新加載頁面。 如果那是您想要的,請嘗試此
綁定的處理程序submit
表單,而不是事件click
按鈕的事件並返回false
,這將阻止form
提交
$('#main-form').on('submit', function () {
$(this).valid(); // do your validation here
$(this).ajaxSubmit(options); // then call the ajax function
return false;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.