S
S
Silverviql2018-06-01 11:20:33
Yii
Silverviql, 2018-06-01 11:20:33

How to send data using ajax method in modal window in yii2?

The button opens a modal window

<div class="zakaz-reminderForm">
    <?php $form = ActiveForm::begin([
        'id' => 'shippingZakaz'
    ]); ?>
    <?= $form->field($comment, 'id_user')->hiddenInput(['value' => Yii::$app->user->id])->label(false) ?>
    <?= $form->field($comment, 'id_zakaz')->hiddenInput(['value' => $model])->label(false) ?>

    <?= $form-> field($comment, 'comment')->textInput(['placeholder' => 'Что', 'class' => 'inputForm', 'style' => 'float:left'])->label(false) ?>

    <?= $form->field($comment, 'date')->widget(DateTimePicker::className() ,[
        'pluginOptions' => [
            'autoclose'=>true,
            'startDate' => 'php Y-m-d H:i:s',
            'todayBtn' => true,
            'todayHighlight' => true,
        ],
        'options' => [
            'placeholder' => 'Срок',
        ],
    ])->label(false) ?>




    <div class="form-group">
        <?= Html::submitButton('Отправить', ['class' => 'action']) ?>
    </div>
    <?php ActiveForm::end(); ?>

Everything works, the data is sent and saved, but when the sambit button is called, the page is reloaded, I want to make sure that the data is simply sent to the database and the modal window closes.

Added a script to the modal window form after the activeform

<?php
    $js = <<<JS
     $('form').on('beforeSubmit', function(){
   var data = $(this).serialize();
   $.ajax({
      url: '/comment/create-reminder',
      type: 'POST',
      data: data,
      success: function(res){
         console.log(res);
      },
      error: function(){
         alert('Error!');
      }
   });
   return false;
     });
JS;

    $this->registerJs($js);
    ?>

Which, as far as I understand, intercepts events after pressing the button and sends the data itself.
But I can't figure out what to put in the url to send.
Function in the controller.
public function actionCreateReminder($id)
    {
        $model = $id;
        $comment = new Comment();
        $notification = new Notification();

        if ($comment->load(Yii::$app->request->post()) && $comment->validate()) {
            $comment->save();//сохранение напоминаниея
            if (!$comment->save()) {
                print_r($comment->getErrors());
            } else {
                if(Yii::$app->request->isAjax){
                    if ($comment->load(Yii::$app->request->post()) && $comment->validate()) {
                        if (!$comment->save()) {
                            print_r($comment->getErrors());
                        }
                        Yii::$app->session->addFlash('update', 'Напоминание успешно создано');
                    }
                    return $this->redirect(['zakaz/admin', '#' => $model->id_zakaz]);
                }
                /** @var $model \app\models\Zakaz */
                Yii::$app->session->addFlash('update', 'Напоминание успешно создано');
                $notification->getByIdNotificationComments( '13', $comment, $id_sotrud_put= null,$zakaz= null);
                $notification->getSaveNotification();
            }
            return $this->redirect(['zakaz/admin', '#' => $model->id_zakaz]);
        }


        return $this->renderAjax('create-reminder', [
            'model' => $model,
            'comment' => $comment
        ]);
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2018-06-01
@butteff

For ajax validation:
1. In ActiveForm::begin() you need to add 'enableAjaxValidation' => true to the view,
2. In the controller, add a construction for ajax validation:

if (Yii::$app->request->isAjax && $model->load(Yii::$app->request>post())) {  // если получаем AJAX и POST запрос
      return ActiveForm::validate($model); // выполняем валидацию формы 
   }

3. To submit a form via ajax, I always write my own js scripts, where I do preventDefault( ) for the button, collect data from the form and send an ajax request - the main thing here is to collect all the form data and __csrf-token and pass it in the request, otherwise the backend will simply throw the request as invalid and not process it.
4. Closing the popup is easy, I understand you will be using bootstrap. Those. The submit button click code should look something like this:
$('.submit-button).click(function(e){
   e.preventDefault();
   // отправка аякса и потом:
   $('#popupselector').modal('hide');
});

L
LAV45, 2018-06-03
@LAV45

You can use the lav45/yii2-ajax-create component

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question