Answer the question
In order to leave comments, you need to log in
How to solve the problem in ajax?
There is this chat:
<div class="chat">
<div class="chat-title">Чат</div>
<div class="chat-block">
<?php foreach ($coments as $com) {
$uss = User::find()->where(['id' => $com->user_id])->one();
?>
<div class="com-box">
<div class="sizik-com"></div>
<div class="com-name"><?= $uss->username ?></div>
<div class="com-text"><?= $com->text; ?></div>
</div>
<?php } ?>
</div>
<div class="coments-block">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($coment, 'text')->textarea(['class' => 'com-inp', 'name' => 'coment', 'row' => 4, 'placeholder' => 'Оставьте комментарии...'])->label('', ['class' => 'com-title']); ?>
<button type="submit" class="btn-all2 btn-jiber"><img class="send-img" src="/img/send.png" alt=""></button>
<?php ActiveForm::end(); ?>
</div>
</div>
$('form').on('beforeSubmit', function(){
var data = $(this).serialize();
$.ajax({
url: '/site/index',
type: 'POST',
data: data,
success: function(res){
console.log(res);
},
error: function(){
alert('Error!');
}
});
return false;
});
public function actionIndex()
{
if(Yii::$app->user->isGuest){
return $this->redirect(['login']);
}
$coment = new Coment();
$com = $_POST['coment'];
$coment->text = $com;
$coment->user_id = Yii::$app->user->id;
$coment->save();
$coments = Coment::find()->orderBy(['id' => SORT_DESC])->all();
$veb = Vebinar::find()->one();
$this->layout = '@app/views/layouts/main2.php';
return $this->render('index', [
'veb' => $veb,
'coment'=>$coment,
'coments'=>$coments,
]);
}
Answer the question
In order to leave comments, you need to log in
On the server side, return the newly created record (naturally in json format), further in this block
success: function(res){
//манипуляции с данными
},
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question