D
D
djienbaev972020-05-02 20:19:43
JavaScript
djienbaev97, 2020-05-02 20:19:43

how to submit ajax form yii2?

Guys help me, I'm trying to submit a form without reloading the page, here is the form:

<?php $form = ActiveForm::begin();?>
                                        <?= $form->field($coment, 'text')->textarea(['class' => 'com-inp', 'name' => 'coment', 'row' => 4, 'placeholder' => 'Өз пікіріңізді жазыңыз...'])->label('', ['class' => 'com-title']); ?>
                                        <?php echo Html::submitButton('Send', ['class' => 'btn btn-success']);?>
                                        <?php ActiveForm::end();?>


script file:
$('form').on('beforeSubmit', function(){
    var data = $(this).serialize();
    $.ajax({
        url: '/site/coments',
        type: 'POST',
        data: data,
        success: function(res){
            console.log(res);
        },
        error: function(){
            alert('Error!');
        }
    });
    return false;
});


and controller:
public function actionComents(){
        $coment = new Coment();
        $com = $_POST['coment'];
        $coment->text = $com;
        $coment->user_id = Yii::$app->user->id;
        if($coment->save(false)){
            Yii::$app->response->redirect(Url::to('/'));
        }else{
            return $this->redirect(['/site?error=1']);
        }
    }


This is how I save it in the controller, and I would also like to display the saved data on the same page without reloading. Well krch here the comment is sent and should be displayed immediately, it works for me without ajax with a reboot

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2020-05-02
@Elgorm

https://webformyself.com/yii2-ajax/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question