[英]Ajax form submitting twice with Yii 2
I've looked around and none of the other similar posts have helped me. 我环顾四周,其他类似的帖子都没有帮助过我。 I have built an AJAx
based form in Yii 2
and jQuery
and it seems it submits the form twice. 我在Yii 2
和jQuery
构建了一个基于AJAx
的表单,似乎它提交了两次表单。
My form: 我的表格:
$form = ActiveForm::begin([
'id' => 'company_form',
'ajaxDataType' => 'json',
'ajaxParam' => 'ajax',
'enableClientValidation' => false
]);
My JS code: 我的JS代码:
$(document).ready(function() {
/* Processes the company signup request */
$('#company_form').submit(function() {
signup('company');
return false;
});
})
function signup(type) {
var url;
// Set file to get results from..
switch (type) {
case 'company':
url = '/site/company-signup';
break;
case 'client':
url = '/site/client-signup';
break;
}
// Set parameters
var dataObject = $('#company_form').serialize();
// Run request
getAjaxData(url, dataObject, 'POST', 'json')
.done(function(response) {
//.........
})
.fail(function() {
//.....
});
// End
}
Shouldn't the standard submit be stopped by me putting the return: false;
我不应该通过return: false;
标准提交停止return: false;
in the javascript code? 在JavaScript代码?
Why is it submitting twice? 为什么要提交两次?
More Info: However the strange thing is, that only appears to happen the first time; 更多信息:然而奇怪的是,这似乎只是第一次发生; if I hit submit again it only submits once; 如果我再次点击提交它只提交一次; but if I reload the page and hit submit it will do it twice again. 但如果我重新加载页面并点击提交,它将再次执行两次。
You may need to change your code like below: 您可能需要更改以下代码:
$('#company_form').submit(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
signup('company');
return false;
});
http://api.jquery.com/event.stoppropagation/ http://api.jquery.com/event.stoppropagation/
http://api.jquery.com/event.stopimmediatepropagation/ http://api.jquery.com/event.stopimmediatepropagation/
Next JS will works with any state of 'enableClientValidation'
: 下一个JS将适用于任何'enableClientValidation'
状态:
$('#company_form').on('beforeSubmit', function (e) {
signup('company');
return false;
});
https://yii2-cookbook.readthedocs.io/forms-activeform-js/#using-events https://yii2-cookbook.readthedocs.io/forms-activeform-js/#using-events
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.