Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 : Vote for a Post in AJAX or Pjax

I'm a begginer in Yii2 framework.

I work on a forum :

In the forum/posts method, there is a list of posts about the topic.

Each Post have a score which I want up and down in AJAX.

In my view posts.php, I open a Pjax block :

<?php Pjax::begin(); ?>
      Votes : <?= $val['score'] ?>
      <?= Html::a('+', ['/post/voteup','id'=>$val['id']]) ?>
      <?= Html::a('-', ['/post/votedown','id'=>$val['id']]) ?>
<?php Pjax::end(); ?>

In my PostController :

public function actionVoteup($id){
    //Update request
    $postRepo=new PostRepository();
    $postRepo->vote('plus', "id=$id");
    $post=$postRepo->getAll("id=$id");

    return $this->renderAjax('vote', ['id'=>$id, 'score'=>$post[0]['score']]);

}

You can see I return the Vote.php view in Ajax, same code Pjax.

<?php Pjax::begin(); ?>
    Votes : <?= $score ?>
    <?= Html::a('+', ['/post/voteup','id'=>$id]) ?>
    <?= Html::a('-', ['/post/votedown','id'=>$id]) ?>
<?php Pjax::end(); ?>

The update request is OK but I have some problems/questions :

  • Ex : I want to up the 2nd post score, I click, OK, I click a second time, the part of view which is refresh is the 1st Post score (but in database, it's the good score updated). I think the problem is about my part of view that I return in my actionVoteup(). Should I return forum/posts or post/vote ?

  • When I click in the link, my URL is : post/voteup ; how can I return in the original URL forum/posts ?

I don't really understand how works Pjax, and I didn't find good examples about its utilisation.

Thanks for your replies :)

like image 255
AHAV Avatar asked Dec 11 '25 13:12

AHAV


1 Answers

You need to add 'enablePushState' => false in Pjax attribute.

Like as

<?php Pjax::begin(['enablePushState' => false]); ?>

For more info. Visit this Demo

like image 99
GAMITG Avatar answered Dec 14 '25 04:12

GAMITG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!