简体   繁体   中英

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.

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.

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM