Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 682
Brett Avatar asked Nov 27 '14 17:11

Brett


2 Answers

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/

like image 154
Ali MasudianPour Avatar answered Sep 18 '22 23:09

Ali MasudianPour


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

like image 35
Egorrishe Avatar answered Sep 19 '22 23:09

Egorrishe