Yii2: Submit event is triggered twice #4955

Created on 11 Sep 2014  路  5Comments  路  Source: yiisoft/yii2

When a form is submitted by clicking on the "submit" button, the script submits the form again.

When there is an on('submit') or on('beforeSubmit'), the function is executed twice.

docs

Most helpful comment

The expected way should be

$("#form").on('beforeSubmit.yii', function(e) {
    $.post($(this).attr("action"), $(this).serialize())
        .done(function(result) {
            $('#modal').modal('hide');
        })
        .fail(function() {
            alert("Error.");
        }
    );
    return false;
});

All 5 comments

It's expected that the submit event is triggered twice: during the first time validation will be performed; if the validation succeeds, it will submit the form, which again triggers the submit event.
The beforeSubmit event is only triggered once.

Thank you @qiangxue

This change may cause some difficulty for developers.

It is worth documenting somewhere, the correct format to submit forms by AJAX.

I do not know if it's the best way, but I'm doing this way (besides beforeSubmit already used before the change, it was necessary to add on('submit')):

$("#form").on('beforeSubmit', function(e) {
    $.post($(this).attr("action"), $(this).serialize())
        .done(function(result) {
            $('#modal').modal('hide');
        })
        .fail(function() {
            alert("Error.");
        }
    );
}).on('submit', function(e){
    e.preventDefault();
});

Thanks. Will add this to the guide.

@thiagotalma
Thanks for your help. You figure this out right. this was creating problem.

The expected way should be

$("#form").on('beforeSubmit.yii', function(e) {
    $.post($(this).attr("action"), $(this).serialize())
        .done(function(result) {
            $('#modal').modal('hide');
        })
        .fail(function() {
            alert("Error.");
        }
    );
    return false;
});
Was this page helpful?
0 / 5 - 0 ratings

Related issues

kminooie picture kminooie  路  3Comments

MUTOgen picture MUTOgen  路  3Comments

skcn022 picture skcn022  路  3Comments

SamMousa picture SamMousa  路  3Comments

psfpro picture psfpro  路  3Comments