dgtal
dgtal

Reputation: 303

Ajax form gets submitted multiple times

I have an action in my controller which submits a new model. The form is in a modal popup and i need a full ajax validation. Everything works except the form is submitted multiple times continuosly. It works if i remove the yiiActiveForm('validate') command, but i need it to validate before the submission.

$('#myformid').off('submit').on('submit', function(e){
    e.preventDefault();
    e.stopImmediatePropagation();


    var form = $(this);
    var formData = form.serializeArray();
    form.data('yiiActiveForm').submitting = true;
    form.yiiActiveForm('validate');

    $.ajax({
        url: form.attr("action"),
        type: form.attr("method"),
        data: formData,
        success: function (data) {

            if(data !== false){
                $('#modal-add-associate').modal('hide');
            }
        },
        error: function () {

        }
    });
    return false;

});

The form starts with

$form = ActiveForm::begin(['enableAjaxValidation' => true,'validationUrl'=> $validationUrl]); 

So usually is validated by ajax with a custom url (and it works except on submit). How can i launch the validation when the form is getting submit?

Upvotes: 0

Views: 538

Answers (1)

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23740

You should use beforeSubmit event rather than submit above all, as you are using the activeform and Yii2 ActiveForm provides you with the following form events

Available events are:

Read More about ActiveForms

Looking at your javascript and the problem you don't need these lines

form.data('yiiActiveForm').submitting = true;
form.yiiActiveForm('validate');

because if you are using a submit type button for submitting the form the validation is automatically triggered as the option validateOnSubmit is by default true for the ActiveForm so you should remove them.

Make sure the Active Form has a submit type button the form should look like below

$form = ActiveForm::begin(['enableAjaxValidation' => true,'validationUrl'=> $validationUrl]);

//Your fields
//.....
//.....
echo Html::submitButton('Submit', ['class' => 'btn']); 
ActiveForm::end();

And you need to revise your javascript, you dont need to use .off().on() as the beforeSubmit will be called only once the form is validated and passes the validation, and you are using type option in ajax call, which is an alias for method. You should use type if you're using versions of jQuery prior to 1.9.0. which isnt your case i think. ifyou are using the latest Yii version 2.0.16 then it includes Jquery 3.3.1 by default via yii\web\JqueryAsset so you can change it to method.

$('#myformid').on('beforeSubmit', function (e) {
    e.preventDefault();

    var form = $(this);
    var formData = form.serializeArray();

    $.ajax({
        url: form.attr("action"),
        method: form.attr("method"),
        data: formData,
        success: function (data) {
            if (data !== false) {
                $('#modal-add-associate').modal('hide');
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(jqXHR, textStatus, errorThrown);
        }
    });
    return false;
});

Upvotes: 2

Related Questions