6

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.

Brett
  • 19,449
  • 54
  • 157
  • 290
  • Does it send ajax request twice in firebug? – Ali MasudianPour Nov 27 '14 at 17:55
  • 1
    @AliMasudianPour Yes, when I watch the console the request is sent twice. 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. – Brett Nov 27 '14 at 17:57

2 Answers2

11

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/

Ali MasudianPour
  • 14,329
  • 3
  • 60
  • 62
  • 1
    I have same problem. The form has `'enableAjaxValidation' => true, 'validateOnSubmit' => true`, but still the form is submitted twice even with the code you provided. It's submitted twice only when there's no errors. – jeesus Oct 02 '15 at 14:04
1

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

Egorrishe
  • 21
  • 5