I
I
Ivan Gordienko2020-04-17 11:19:14
JavaScript
Ivan Gordienko, 2020-04-17 11:19:14

GetFlash + submit Yii2 by ajax?

Good day. I'm learning Yii2 and touched upon the implementation of such a thing as comments.
Comments are added by pressing the "send" button, go to the admin panel, where they are approved and fast.
The idea is that when a comment is added, the user is notified that the comment is being checked, the text input field is cleared and everyone is happy. Now it was possible to implement sending a comment to the admin panel only through page refresh. It would be desirable to make on ajax.

Comment code -

<?php if(!Yii::$app->user->isGuest):?>
        <div class="leave-comment">
            <?php if(Yii::$app->session->getFlash('comment')):?>
                <div class="alert alert-success" role="alert">
                    <?= Yii::$app->session->getFlash('comment'); ?>
                </div>
            <?php endif;?>

            <?php $form = \yii\widgets\ActiveForm::begin([
                'action'=>['site/comment', 'id'=>$article->id],
                'options'=>['class'=>'form-horizontal contact-form', 'role'=>'form']])?>

            <div class="form-group">
                <div class="col-md-12" style="padding: 0;">
                    <?= $form->field($commentForm, 'comment')->textarea(['class'=>'form-control comment-form', 'placeholder'=>'Ваше сообщение'])->label(false)?>
                </div>
            </div>

            <button type="submit" class="btn send-btn">Отправить</button>
            <?php \yii\widgets\ActiveForm::end();?>

        </div>
    <?php endif;?>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
topalek, 2020-04-17
@topalek

$this->registerJs(
        <<<JS
    
    $('form').on('beforeSubmit',function(event) {
        var yiiForm = $(this);    
        yiiForm.find('.has-error').removeClass('has-error');
        yiiForm.find('.help-block').html('');
        
        $.ajax({
            url: yiiForm.attr('action'),
            type: 'post',
            data: yiiForm.serialize(),
            success: function(result) {
                if(result.errors) {
                     jQuery.each(result.errors, function(id, error) {
                         $('.field-' + id).addClass('has-error').find('.help-block').html(error);
                     });
                }
                
                if(result.status == true){
                    // show message
                }
            } 
        });
        
        return false;

    });
JS
    );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question