You are viewing revision #2 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.
Normally, after clicking the delete button in gridview, the record will be deleted and the page will refresh, but the page number in query string is lost. This is not always the case we expect.
How to refresh current page with pjax after deleting the record? It seems there is no simple solutions, This is my way, it works well, although it is not clean
- Controller file
public function actionDelete($id)
{
$this->findModel($id)->delete();
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ['success' => true];
}
return $this->redirect(['index']);
}
- index.php(view file)
<?php
$this->registerJs("
$(document).on('ready pjax:success', function() {
$('.pjax-delete-link').on('click', function(e) {
e.preventDefault();
var deleteUrl = $(this).attr('delete-url');
var pjaxContainer = $(this).attr('pjax-container');
var result = confirm('Delete this item, are you sure?');
if(result) {
$.ajax({
url: deleteUrl,
type: 'post',
error: function(xhr, status, error) {
alert('There was an error with your request.' + xhr.responseText);
}
}).done(function(data) {
$.pjax.reload('#' + $.trim(pjaxContainer), {timeout: 3000});
});
}
});
});
");
?>
<?php Pjax::begin(['id' => 'my_pjax']); ?>
<div class="shop-index">
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'id',
[
'class' => 'yii\grid\ActionColumn',
'buttons' => [
'update' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [
'class' => 'pjax-update-link',
'title' => Yii::t('yii', 'Update'),
]);
},
'delete' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-trash"></span>', false, [
'class' => 'pjax-delete-link',
'delete-url' => $url,
'pjax-container' => 'my_pjax',
'title' => Yii::t('yii', 'Delete')
]);
}
],
],
],
]); ?>
</div>
<?php Pjax::end(); ?>
Is there a way without jquery to catch the pjax success event?
Thanks!
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.