Submit through Ajax

I intend to capture selected checkboxes from a gridview and possibly delete them.

Problem is the selected items are rightly identified but the controller action does not run. The problem seems to lye in the "$.post" section in javascript.

Thanks pals





<?= Html::submitButton(' Delete ALL Checked', ['class' => 'btn btn-primary', 'id'=>'modalButton']) ?>


	<?php //ActiveForm:: end () ; ?>

		

   <?= GridView::widget([

        'dataProvider' => $dataProvider,

		'id' => 'meterreading',

        'filterModel' => $searchModel,

        'columns' => [

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


            //'id',

            'meter_no',

            'meter_reading',

            'reading_date:date',

			

			[

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

					'header' => Html::checkBox('selection_all', false, [

						'class' => 'select-on-check-all',

						'label' => 'Check All',

					]),

				'checkboxOptions' => function ($model, $key, $index, $column){

				return [ 

				"value" => $model->id,//$model->groupid

				"checked" => 0];//	$model->status==10?1:0]

				}

			],

			

			

            //'user_reading',

            // 'year',


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

        ],

    ]); ?>




<?php Pjax::end(); ?>	

</div>


<?php

$script = <<< JS

	$ (document ).ready (function() {

		$('#modalButton').on('click',function() {

			alert('1');		//prints right

			var keys = $('#meterreading').yiiGridView('getSelectedRows');

			alert(keys);	//prints right

			$.post({

				url: '/meter-readings/bulk-delete', // your controller action

				data: {keylist: keys},

				dataType: 'json',

				success: function(data) {alert('I did it! Processed checked rows.')},

			});

		});

	});

JS;

$this -> registerJs ($script );

?>


<?php


	public function actionBulkDelete(){

		if (isset ($_POST ['keylist' ])) {

		$keys = \yii\helpers\Json::decode($_POST['keylist']);

		echo $keys;

	}




have you tried using ajax() instead of .post()? I’d also use Url::to() so you can ensure the url is always correct. The last thing I would do differently is In your controller I’d use return instead of echo.




<?php

Pjax::end();

$this->registerJs("jQuery('#modalButton').on('click',function() {

    jQuery.ajax({

        url: '" . \yii\helpers\Url::to(["/meter-reading/bulk-delete"]) . "',

        data: {keylist: jQuery('#meterreading').yiiGridView('getSelectedRows')},

        type: 'POST',

        dataType: 'json',

        success: function(data) {

             console.log(data);

        }

    });

 });");