Ajax form submitting twice with Yii 2

こ雲淡風輕ζ 提交于 2019-12-10 14:19:45

问题


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.

My form:

$form = ActiveForm::begin([
    'id' => 'company_form',
    'ajaxDataType' => 'json',
    'ajaxParam' => 'ajax',
    'enableClientValidation' => false
]);

My JS code:

$(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; in the javascript code?

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.


回答1:


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.stopimmediatepropagation/




回答2:


Solution common

Next JS will works with any state of 'enableClientValidation':

$('#company_form').on('beforeSubmit', function (e) {
    signup('company');
    return false;
}); 

https://yii2-cookbook.readthedocs.io/forms-activeform-js/#using-events



来源:https://stackoverflow.com/questions/27176465/ajax-form-submitting-twice-with-yii-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!