[SOLVED] Modify Ajax request before it's sent

I am creating a Ajax button in my _form.php with:

CHtml::ajaxButton('<-- copy text', array('/messages/ajaxMessageText', 'type'=>'25', 'id'=>'16', 'divId'=>$j),

	array('success'=>'js:ajaxSuccess', 'beforeSend'=>'js:ajaxBeforeSend', 'error'=>'js:ajaxError'));

The ‘id’ variable is not known when the button is created as it is related to a dropdown menu. I tried to set the ‘beforeSend’ function to modify the ‘id’ variable before the request is sent, but this seems impossible to do.

What is the correct way doing this?



Check the jquery documentation: you can set data options.

Chtml::options('label', array('url'), array('success'=>'', 'data'=>'js:...'));

Thanks for your answer.

It seems like ‘data’ is used when i create the ajaxButton, much like how I did it before. What I need to do is modifying the content of the Ajax request when the button is clicked, before the request is sent.

What am I missing?

You can write a js function, or use a js variable in data. In before send set this variable and it should work

Thank you, I got it working :)

That’s great! Can you post your solution for future readers?


I could not find a way to modify existing variables in the request so my solution just adds new variables.

All the following code lives in the _form.php view.

Register the JavaScript function that will process the request:


$js = Yii::app()->getClientScript();

$js->registerScriptFile(Yii::app()->baseUrl . '/js/jquery.tools.min.js');



	'function modifiyId(type, id) {

		// dd is a dropdown list

		var dd = $("#Messages" + type + "_dropdown" + id);

		return "id=" + dd.val();




The returned string from this function is appended to the Ajax request.

The Ajax button is created with:

echo CHtml::ajaxButton('Button title', array('/messages/ajaxMessageText', 'type'=>'25', 'divId'=>$j,),

	array('success'=>'js:ajaxSuccess', 'error'=>'js:ajaxError',

		'data'=>"js:modifiyId('25', $j)"));

The type and divId variables are appended to the Ajax request right when the button is created, but the function associated with the field data is called when the button is pushed. This makes it possible to append more varialbes to the request string after the button has been created.