Cgridview Custom Button Action Using Ajax Instead Of Get

I created a custom button in my grid following the excellent tutorial at:

http://www.yiiframew…s-in-cgridview/

The actions of these custom buttons are called using get variables but I need to use ajax instead. Just for testing, I tried to mimic what the delete button does. I included in my custom button:





'buttons'=>array

  (

       'customDelete' => array

           (

             ...

             'url'=>'Yii::app()->controller->createUrl("delete",array("id"=>$data->primaryKey))',

           ),

		...



That is the same code that the CButtonColumn delete button uses, and I am calling the same delete function in my controller.





public function actionDelete($id)

   {

   	if(Yii::app()->request->isPostRequest)

   	{

   		// we only allow deletion via POST request

   		$this->loadModel($id)->delete();


   		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

   		if(!isset($_GET['ajax']))

       		$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

   	}

   	else

   		throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

   }



The problem is that when I try to use my custom delete button, the action throws the exception saying it is not a POST request.

So how could I make my button work so it calls the action using POST/Ajax ?

You are missing one vital part… the default "delete" button does have a jQuery script that is making the actual ajax call.

In that case, how can I make the same with my custom button? (make the ajax call for the action and refresh the grid, like the default delete button does)

Digging into the CButtonClass I found this (which I think it is the ajax call you mention):





$this->buttons['delete']['click']=<<<EOD

function() {

	$confirmation

	var th=this;

	var afterDelete=$this->afterDelete;

	$.fn.yiiGridView.update('{$this->grid->id}', {

		type:'POST',

		url:$(this).attr('href'),$csrf

		success:function(data) {

			$.fn.yiiGridView.update('{$this->grid->id}');

			afterDelete(th,true,data);

		},

		error:function(XHR) {

			return afterDelete(th,false,XHR);

		}

	});

	return false;

}

EOD;

		}

	}



The problem is that I don’t understand ajax. I imagine I have to write something similar using registerscript. Maybe someone who understands better how this ajax thing works could share the code to make the button call the function using ajax. Also, if there a link where I could learn more on how to use those strange ajax functions that start with “$.” I would really appreciate it.

Thank you!

Yes that is the PHP part that is a combination of PHP and javascript… but if you check the page source of the generated page with a default delete button, you will get there the resulting function completely in javascript / jQuery.

Of course the easiest thing would be to give you the code that works but as you say you don’t understand nor even know how or what it does, in my opinion it’s better for you to learn first a bit about jQuery so you can understand what that code does.

Try to find some basic jQuery tutorials so at lest you understand a bit, of course for this you would need to know at least the basics of javascript, too.

I was hopping yii had a php wrapper to do ajax calls. Writing all that js directly is a little bit messy.

I looked at the actual webpage code where the regular delete button is:

The link looks like a regular link:




<a class="delete" title="Delete" rel="tooltip" href="/user/delete/id/1"><i class="icon-trash"></i></a>



then there is this js code:





$(document).on('click','#user-grid a.delete',function() {

	if(!confirm('are you sure you want to delete?')) return false;

	var th=this;

	var afterDelete=function(){};

	$.fn.yiiGridView.update('user-grid', {

		type:'POST',

		url:$(this).attr('href'),

		success:function(data) {

			$.fn.yiiGridView.update('user-grid');

			afterDelete(th,true,data);

		},

		error:function(XHR) {

			return afterDelete(th,false,XHR);

		}

	});

	return false;

});



According to one website this is a standard ajax call:





$.ajax({

    type:"POST",

    url: "ajaxpage.php",

    cache:false,

    data: "firstnumber="+firstnumber+"&secondnumber="+secondnumber,

    success: function(data){

            $(".result").empty();

            $(".result").html(data);

        }

    });

   return(false);



So, for what I understand what that js script does is to stop the link and instead call the function (in this case the .fn.yiiGridView.update() function). One of the things I do not understand is why ".fn.yiiGridView.update"? I am guessing that the function not only does the ajax call but updates the data in the grid. But how someone is supposed to find out the .fn.yiiGridView.update function name? I can not find it in the yii documentation (or maybe I am not looking in the right place).

I finally solved what I needed to do. Here is the code (if anyone needs it):





'buttons'=>array

            (

                'myCustomButton' => array

                (

                    'label'=>'my button label',

                    'click'=>"function(){

                                    $.fn.yiiGridView.update('user-grid', {

                                        type:'POST',

                                        url:$(this).attr('href'),

                                        success:function(data) {

                                              $('.output').html(data);

                                              $.fn.yiiGridView.update('user-grid');

                                        }

                                    })

                                    return false;

                              }

                              ",

                    'url'=>'Yii::app()->controller->createUrl("myAction",array("id"=>$data->primaryKey))',

                ),



  • Change user-grid to the name of your grid

  • The statement $(’.output’).html(data); will print in a div called output anything your action echoes.

Nice…

Yes there is no documentation for that function… this is a method of the CGridView JS code located in jquery.yiigridview.js file…

use like

‘buttons’=>array(

‘Update’ =>array(

‘imageUrl’=>Yii::app()->request->baseUrl.’/images/up.png’,

‘url’=>‘Yii::app()->createUrl(“user/update”, array(“id”=>$data->id) )’,

‘click’=>"function() {

if(!confirm(‘Update ?’)) return false;

$.fn.yiiGridView.update(‘user-grid’, {

type:‘POST’,

url:$(this).attr(‘href’),

success:function(text,status) {

$.fn.yiiGridView.update(‘user-grid’);

}

});

return false;

}",

),

),