R
R
Ruslan Absalyamov2019-04-02 11:02:41
Yii
Ruslan Absalyamov, 2019-04-02 11:02:41

Why is my ajax submit event happening twice?

When submitting a form via ActiveForm. The point is that you only need to send the image to the server. In order not to try to do everything manually through $_FILES, I'm trying to implement everything dynamically, without reloading the page.
Here is the form

<?php $form = \yii\widgets\ActiveForm::begin([
                        'id' => 'avatar-form',
                        'action' => Url::to(['profile/upload-avatar', 'id' => $user->id]),
                        'options' => [
                                'enctype' => 'multipart/form-data',
                            'name' => 'avatar-form'
                        ],
                    ]) ?>
                    <?= $form->field($user, 'file')->fileInput(['class' => '_disabled', 'id' => 'uploadAvatar']); ?>
                    <?= \yii\helpers\Html::submitButton('отправить', ['id' => 'avatar-form_button']) ?>
                    <?php \yii\widgets\ActiveForm::end() ?>

Well, you probably don’t need to write in the controller, probably only the form itself is needed
/**
     * @brief Загрузка аватарки
     * @param $id
     * @return bool
     */
    public function actionUploadAvatar($id)
    {
        if (\Yii::$app->request->isAjax) {
            $model = User::findOne($id);
            $model->scenario = User::SCENARIO_UPLOAD_AVATAR;
            $model->file = UploadedFile::getInstance($model, 'file');

            $model->avatar = $model->file->extension;
            if ($model->save()) {
                $model->uploadFile($id);
            }
        }
    }

And for now, a simple Js
$('#avatar-form').submit(function (e) {
    debugger;
    e.preventDefault();
    console.log(form);
  });

In response I receive
w.fn.init [form#avatar-form]
index:1751 w.fn.init [form#avatar-form]

If you look at the event, then they are different. The very first one has originalEvent
5ca3171eb54e5433647193.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Moses Fender, 2019-04-02
@rusline18

And, well, here is the solution. One submit is done by Yii, the second one by jQuery.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question