Delete comment via pjax


on my page (own) comments should be edited and deleted via Pjax. While editing works like a charm, deleting doesn’t. The comment is deleted, but it redirects to at least 2 other actions with an error at the end.


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

echo Html::a('edit', ['cl/edit_comment', 'cid' => $cid, 'id' => $comment->id])." | ".Html::a('delete', ['cl/delete_comment', 'cid' => $cid, 'id' => $comment->id]);

Pjax::end(); ?>


$comment = Comment::findOne($id);


return $this->render(['frage', 'cid'=>$cid], 302, false);

Also redirect instead of render doesn’t work. On editing my comment, I work with return $this->renderAjax(’_name’) with works nice, but how can I render a blank view after deleting? Or any other idea? Thanks!

You need to have either JavaScript or jQuery to perform this task. You didn’t put enough code to give you a full definitive answer so I’m going to make a lot of assumptions.

You have a lot of comments on a single page

The comments are wrapped in a single pjax container

You want to be able to delete a single comment and stay on the page.

The link would be something like the following. Note you must use the jQuery for it to work. You should remove the pjax wrapping container as well.

Html::a('delete',FALSE, ['class'=>'ajax-delete', 'data-url'=>Url::to(['cl/delete_comment', 'cid' => $cid, 'id' =>$comment->id]]));

jQuery on the main page. This should only be on the main page… not on each comment. Also each comment shouldn’t have a pjax wrapper as it’s not needed.

jQuery(document).on('click', '.ajax-delete', function(e) {


    	url: jQuery(this).data('url'),

    	type: 'POST',

    	dataType: 'json',

    	success: function(data) {

        	jQuery.pjax.reload({container: '#pjax-container'});




The controller shouldn’t redirect it should only return.


\Yii::$app->response->format = Response::FORMAT_JSON;

return [];

Instead of using pjax reload you can just remove the comment in the success portion.  It may be a better option if you don't need to refresh all the comments.