Gridview delete action does not send ajax request with Pjax

Hello Friends.

I have face one problem while deleting the row of


Gridview

with request of ajax using


Pjax

. but when i filtered or sort the Grid, than i delete row so after the deleting row page redirect to index action. and all the filter and sorting reseted.

I try to remove


redirect

method in controller but still not work.

How can prevent redirecting to


index

or send ajax request same as Yii 1.0 gridview ?

my code is.

view file




	<?php \yii\widgets\Pjax::begin([

				'id' => 'pjax-list',

				'enablePushState' => false,

				'enableReplaceState' => false,

		]); ?>

		<?= GridView::widget([

			'dataProvider' => $dataProvider,

			'filterModel' => $searchModel,

			'columns' => [

				['class' => 'yii\grid\SerialColumn'],

				'stu_category_name',

				//['class' => 'yii\grid\ActionColumn'],

				[

					'class' => 'yii\grid\ActionColumn',

					'template' => '{view} {delete}',

					'buttons' => [

							'view' => function ($url, $model) {

									return ((Yii::$app->user->can("/student/stu/view")) ? Html::a('<span class="glyphicon glyphicon-eye-open"></span>', $url, ['title' => Yii::t('app', 'View'),]) : '');

								},

							'delete' => function ($url, $model) {

									return ((Yii::$app->user->can("/student/stu/delete")) ? Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, ['title' => Yii::t('app', 'Delete'), 'data' => ['confirm' => 'Are you sure you want to delete this item?','method' => 'post'], 'data-ajax' => '1']) : '');

			    			}

					],

				],

			],

		]); ?>

		<?php \yii\widgets\Pjax::end(); ?>

controller file




   public function actionDelete($id)

    {

		$model = StuCategory::findOne($id);

		$model->delete();

		//return $this->redirect(['index']);

    }

You could do something like the following. It’s a basic version of what i use.




$(function() {

	$(document).on('click', '.ajaxDelete', function() {

    	var deleteUrl = $(this).attr('delete-url');

    	var pjaxContainer = $(this).attr('pjax-container');  	

            	$.ajax({

                	url: deleteUrl,

                	type: "post",

                	dataType: 'json',

                	error: function(xhr, status, error) {

                    	alert('There was an error with your request.' + xhr.responseText);

                	}

            	}).done(function(data) {

                            	$.pjax.reload({container: '#' + $.trim(pjaxContainer)});

            	});        	

    	});

});




your delete button would be something like


'delete' => function ($url, $model) {

  return  ((Yii::$app->user->can("/student/stu/delete")) ? Html::a('<span  class="glyphicon glyphicon-trash"></span>', false, ['class'=>ajaxDelete','delete-url'=>$url, 'pjax-container'=>'pjax-list','title'  => Yii::t('app', 'Delete'), 'data' => ['confirm' => 'Are you  sure you want to delete this item?']]) : '');

}



You just need to add the following to each button to work:

class => ‘ajaxDelete’

‘pjax-container’=>‘your-pjax-id’

‘delete-url’=>‘url-to-delete-action’

you can add it to any link/button to delete an item. If you have issues use your log / inspect elements to make sure everything is calling the right links and ID’s.

this is not working…

Check your console. How to check console in Chrome

What isn’t working?

What are the errors?

Is the script registering?

Are you getting undefined elements?

Are there function errors?

Are you putting the JS straight in the page? If so then you should take it out of the function() and bind it to the element. However, this is not ideal and should be registered somewhere to be reusable. However, here is a way to put it straight on the page.




$('.ajaxDelete').on('click', function() {

        var deleteUrl = $(this).attr('delete-url');

        var pjaxContainer = $(this).attr('pjax-container'); 	

                $.ajax({

                        url: deleteUrl,

                        type: "post",

                        dataType: 'json',

                        error: function(xhr, status, error) {

                        alert('There was an error with your request.' + xhr.responseText);

                        }

                }).done(function(data) {

                                $.pjax.reload({container: '#' + $.trim(pjaxContainer)});

                });         	

});



After Pjax update or complete click event not work. and also confirmation of delete is not work.

other one works like

delete of row with ajax (before Pjax complete)

my code

Script

[b]

[/b]




     $('.ajaxDelete').on('click', function(e) {

		    var deleteUrl = $(this).attr('delete-url');

		    var pjaxContainer = $(this).attr('pjax-container');


		        $.ajax({

		                url: deleteUrl,

		                type: 'post',

		               // dataType: 'json',

		                error: function(xhr, status, error) {

		                alert('There was an error with your request.' + xhr.responseText);

		                }

		        }).done(function(data) {

		                        $.pjax.reload({container: '#' + $.trim(pjaxContainer)});

		        });           

        });

Delete button




							'delete' => function ($url, $model) {

									return ((Yii::$app->user->can("/student/stu-master/delete")) ? Html::a('<span class="glyphicon glyphicon-trash"></span>', false, ['class' => 'ajaxDelete', 'delete-url' => $url, 'pjax-container' => 'pjax-list', 'title' => Yii::t('app', 'Delete'), 'data-pjax' => '0']) : '');

				    		}

Thanks @skworden.

after finding bug i get solution of this code.

after that my code is





$this->registerJs("

$(document).on('ready pjax:success', function() {

    $('.ajaxDelete').on('click', function(e) {

		e.preventDefault();

	    var deleteUrl = $(this).attr('delete-url');

	    var pjaxContainer = $(this).attr('pjax-container');

		bootbox.confirm('Are you sure you want to change status of this item?',

			function(result) {

				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({container: '#' + $.trim(pjaxContainer)});

					});

				}

			}

		);           

    });

});

");







		<?php \yii\widgets\Pjax::begin([

				'id' => 'pjax-list',

		]); ?>

		<?= GridView::widget([

			'dataProvider' => $dataProvider,

			'filterModel' => $searchModel,

			'columns' => [

				['class' => 'yii\grid\SerialColumn'],

				'stu_category_name',

				[

					'class' => 'yii\grid\ActionColumn',

					'template' => '{view} {delete}',

					'buttons' => [

							'view' => function ($url, $model) {

									return ((Yii::$app->user->can("/student/stu/view")) ? Html::a('<span class="glyphicon glyphicon-eye-open"></span>', $url, ['title' => Yii::t('app', 'View'),]) : '');

								},

							'delete' => function ($url, $model) {

									return ((Yii::$app->user->can("/student/stu/delete")) ? Html::a('<span class="glyphicon glyphicon-trash"></span>', false, ['class' => 'ajaxDelete', 'delete-url' => $url, 'pjax-container' => 'pjax-list', 'title' => Yii::t('app', 'Delete')]) : '');

				    		}

					],

				],

			],

		]); ?>

		<?php \yii\widgets\Pjax::end(); ?>



above code work fine.

Thank You so much. @[size=2]skworden [/size]

Glad you got it working… i see you are using bootbox alerts. I use this with sweetalert (Boostrap version) and it’s pretty slick looking.

I’d switch the error to your bootbox to keep continuity throughout your program.


error: function(xhr, status, error) {

 bootbox.alert('There was an error with your request.' + xhr.responseText);

}

i like the sweetalert :)