A
A
Artem Prokhorov2021-04-30 19:37:45
AJAX
Artem Prokhorov, 2021-04-30 19:37:45

Why doesn't e.preventDefault() work in Yii2?

Form in view:

<?php $form = ActiveForm::begin(['id' => 'test_form']) ?>
    <?= $form->field($menu, 'name') ?>
    <?= $form->field($menu, 'age') ?>
    <?= Html::submitButton('Click me...', ['id' => 'btn']) ?>
    <?php ActiveForm::end() ?>


js:

let form = document.querySelector('#test_form');
const csrfToken = document.querySelector("[name='csrf-token']").content

form.addEventListener('submit', function(e) {
    e.preventDefault();

    let promise = fetch('/?r=post/show', {
        method: 'POST',
        body: new FormData(this),
        headers: {
            "X-CSRF-Token": csrfToken //  Set the token
        }
    });
    
    promise
        .then(
            data   => {return data.json()}
        )
        .then(
            result => {console.log(result)}
        )
});


The console of errors does not issue not before reboot or after. The result itself returns correctly.

Update:

prevent works on links, for some reason this behavior is only for submitButton/submitInput on forms.

Update 2.0:

In general, I integrated vue,js and prevent works with it, and the code has not changed at all (well, except that I put the function itself in new Vue({});. The reasons for this behavior are still not clear to me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
My joy, 2021-04-30
@t-alexashka

If you need to prevent the form from being submitted, then e.preventDefault();you need to write the listener at the beginning and not at the end.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question