Passing parameters to an ajax link

For creating new models in a form I use the excellent wiki article

http://www.yiiframework.com/wiki/145/cjuidialog-for-create-new-model/

But I’m not sure how to pass parameters so it updates a model?

Link to update




<?php echo CHtml::link('Update classroom', 

    "",

    array(

        'style'=>'cursor: pointer; text-decoration: underline;',

        'onclick'=>"{updateClassroom(); $('#dialogClassroom').dialog('open');}"));

?>



Ajax function




function updateClassroom()

{

    <?php echo CHtml::ajax(array(

            'url'=>array('classroom/update'),

            'data'=> "js:$(this).serialize()",

            'type'=>'post',

            'dataType'=>'json',

            'success'=>"function(data)

            ...



The above displays the update form in a dialog when I use a dummy $id value in the update action controller




	public function actionUpdate($id=null)

	{

		$id=1;

		...



But if I amend the above to pass parameters via the href parameter, the update form is displayed on a separate page rather than in the dialog box

Link to update




<?php echo CHtml::link('Update classroom', 

    array('classroom/update',$model->classroom->id), // sending the id

    array(

        'style'=>'cursor: pointer; text-decoration: underline;',

        'onclick'=>"{updateClassroom(); $('#dialogClassroom').dialog('open');}"));

?>



Ajax function




function updateClassroom()

{

    <?php echo CHtml::ajax(array(

            'url'=>'$(this).attr(\'href\')', // using the passed url

            'data'=> "js:$(this).serialize()",

            'type'=>'post',

            'dataType'=>'json',

            'success'=>"function(data)

            ...



Any ideas?

Thanks, Russ

Try this one:




 <?php echo CHtml::ajax(array(

            'url'=>array('classroom/update', 'id'=>$model->id),

            'data'=> "js:$(this).serialize()",

            'type'=>'post',

            'dataType'=>'json',

            'success'=>"function(data)



Post data will arrive from the post, while get data will be set with the url.

If you use my wiki with success, would you mind to thumb it up? I’d really appreciate it!

Hiya Zaccaria

Oh I have already given it the thumbs up before :)

Sorry I didn’t mention that I was using your code in a CGridView.

I don’t think I can do it that way because I’m using a link in a grid column.




'value'=>'CHtml::link(

		($data["comment"]?$data["comment"]:"(comment)"),

		"",

		array(

			\'style\'=>\'cursor: pointer; text-decoration: underline;\',

			\'onclick\'=>"{updatePaymentComment(); $(\'#dialogPaymentComment\').dialog(\'open\');}"

		)

	);',



I tried using




array("eventClient/updatePaymentComment","id"=>$data["id"], "client_id"=>$data["client_id"], "event_id"=>$data["event_id"]),



as the second parameter instead of ""

So when a user clicks the link, a dialog pops up and they can change the payment or comment. But instead, it goes straight to a separate page.

Thanks, Russ

You should pass the parameter always through the ajax function you attach to the onsubmit, never with ajax link.

I never tried this, but I guess is possible to di something like that:

In the link:


'value'=>'CHtml::link(


                ($data["comment"]?$data["comment"]:"(comment)"),

                "",

                array(

                        \'style\'=>\'cursor: pointer; text-decoration: underline;\',

                        \'onclick\'=>"{updatePaymentComment{$data->id}(); $(\'#dialogPaymentComment\').dialog(\'open\');}"

                )

        );',

You give a different function name for each item. Now, aways in the CGridView, you create a differente function for each update:




function updateClassroom{$data->id}()

{

    <?php echo CHtml::ajax(array(

            'url'=>array('classroom/update', 'id'=>$data->id),

            'data'=> "js:$(this).serialize()",

            'type'=>'post',

            'dataType'=>'json',

            'success'=>"function(data)

            ...



Seen like that looks like a crazy stuff, but this is a winning idea.

Create a widget wich includes all the code in my wiki (ajaxLink + dialog + jscode) and include it in each item.

You will create 10 different functions with 10 different div, is not as much html as you think, and it works perfectly.

Take a look at this implementation: click on the link on the right of each item. It send a message to the hotel, is a different dialog for each hotel, here too there is the problem of passing the id. You can give a look about how looks like the js code.

Please, not that this example is a live site, don’t save anything, plase :)!

I’ve was coding something very similar last night by copying the script from page source :

In the column




array(

	'name'=>'comment',

	'header'=>'Comments',

	'type'=>'raw',

	'value'=>'CHtml::link(

		($data["comment"]?$data["comment"]:"(comment)"),

		"",

		array(

			\'style\'=>\'cursor: pointer; text-decoration: underline;\',

			\'onclick\'=>\'{updatePaymentComment(\'.$data["id"].\');

				$("#dialogPaymentComment").dialog("open");}\'

		)

	);',

),



Then in the function I have




<script type="text/javascript">

function updatePaymentComment(_id)

{

	var _url;

	_url='http://localhost/sumba/eventClient/updatePaymentComment/'+_id;

	

	jQuery.ajax({

		url: _url,

		'dataType':'json',

		'type':'POST',

		'success':function(data)

			{

				if (data.status == 'failure')

				{

					$('#dialogPaymentComment div.divPaymentComment').html(data.div);

					// Here is the trick: on submit-> once again this function!

					$('#dialogPaymentComment div.divPaymentComment form').submit(updatePaymentComment);

				}

				else

				{

					$('#dialogPaymentComment div.divPaymentComment').html(data.div);

					setTimeout("$('#dialogPaymentComment').dialog('close') ",2000);

					$.fn.yiiGridView.update('event-client-grid');

				}


			} ,

		'cache':false});

	return false;


}

</script>



Which displays the dialog with the correct model, but when I click the "save" button nothing happens.

I think its because of the line




	$('#dialogPaymentComment div.divPaymentComment form').submit(updatePaymentComment);



In FireBug when I click save I get the error




POST http://localhost/sumba/eventClient/updatePaymentComment/[object Object]

404 CHttpException



I tried changing the submit to include the _id parameter




	$('#dialogPaymentComment div.divPaymentComment form').submit(updatePaymentComment(_id));




But the javascript goes into an endless loop :(

Any ideas?

Solved it!!

I pass the url as a parameter, then save the url as a global variable

In the column I have




array(

	'name'=>'comment',

	'header'=>'Comments',

	'type'=>'raw',

	'value'=>'CHtml::link(

			($data["comment"]?$data["comment"]:"(comment)"),

			"",

			array(

				\'style\'=>\'cursor: pointer; text-decoration: underline;\',

				\'onclick\'=>\'{updatePaymentComment("\'.


Yii::app()->createUrl("eventClient/updatePaymentComment",

array("id"=>$data["id"], "client_id"=>$data["client_id"], "event_id"=>$data["event_id"]))


.\'"); $("#dialogPaymentComment").dialog("open");}\'

			)

		);',

),



Then the update function is




<script type="text/javascript">

var _updatePaymentComment_url;

function updatePaymentComment(_url)

{

	// If its a string then set the global variable, if its an object then don't set

	if (typeof(_url)=='string')

		_updatePaymentComment_url=_url;


	jQuery.ajax({

		url: _updatePaymentComment_url,

		'data':$(this).serialize(),

		'type':'post',

		'dataType':'json',

		'success':function(data)

			{

				if (data.status == 'failure')

				{

					$('#dialogPaymentComment div.divPaymentComment').html(data.div);

					// Here is the trick: on submit-> once again this function!

					$('#dialogPaymentComment div.divPaymentComment form').submit(updatePaymentComment); // updatePaymentComment

				}

				else

				{

					$('#dialogPaymentComment div.divPaymentComment').html(data.div);

					setTimeout("$('#dialogPaymentComment').dialog('close') ",2000);

					$.fn.yiiGridView.update('event-client-grid');

				}


			} ,

		'cache':false});

	return false;


}


</script>



Cheers, Russ

Nice solution, the only sad point is that you cannot use CHtml::ajax, but the result really worth.

Did you tried something like:


CHtml::ajax(array('url'=>'js:_updatePaymentComment_url'...));

This will allow you to use the Yii method! For have a solution 100% cool

That works :)

Cool, 100% cool

This is what id do:


array(

    'name'=>'comment',

    'header'=>'Comments',

    'type'=>'raw',

    'value'=>'CHtml::link(

        ($data["comment"]?$data["comment"]:"(comment)"),

        Yii::app()->createUrl(

                "eventClient/updateComment",

                array("id"=>$data["id"])

            ),

        array(

            \'style\'=>\'cursor: pointer; text-decoration: underline;\',

            \'class\'=>\'comment-update-link\',

        )

    );',

),

In the controller.




<?php

$js <<<EOD

jQuery('.comment-update-link').click(function(e){

     e.preventDefault();

     jQuery.ajax({

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

                'dataType':'json',

                'type':'POST',

                'success':function(data)

                        {

                                if (data.status == 'failure')

                                {

                                        $('#dialogPaymentComment div.divPaymentComment').html(data.div);

                                        // Here is the trick: on submit-> once again this function!

                                        $('#dialogPaymentComment div.divPaymentComment form').submit(updatePaymentComment);

                                }

                                else

                                {

                                        $('#dialogPaymentComment div.divPaymentComment').html(data.div);

                                        setTimeout("$('#dialogPaymentComment').dialog('close') ",2000);

                                        $.fn.yiiGridView.update('event-client-grid');

                                }


                        } ,

                'cache':false});

        $('#dialogClassroom').dialog('open');


});

EOD;

 Yii::app()->clientScript->registerScript("comment-update", $js);

?>

or you can have this javascript in a separate file, as it does not require any dynamic code.

Controller:


Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl."/js/yourscript.js");

Thank you Asgaroth :)

I couldn’t get it to work though :(

But I discovered that Javascript functions are also a class, so I set the _url property rather than passing as a variable. Which also means I can avoid using a global variable :) The updated wiki is

http://www.yiiframework.com/wiki/204/using-cjuidialog-to-edit-rows-in-a-cgridview/

hi, Russell England

I had the same problem, and I tried to follow your solution. but it doesn’t work.

could you help to check my code below:

my gridview




array(

        //'header'=>'Edit',

        'type'=>'raw',       

        'value'=> 'CHtml::link(\'Edit\',array(\'\'),array(\'title\'=>Yii::app()->createUrl("Order/Update",

		array("id"=>$data->order_id)),\'class\'=>\'order_update\',))',

        ),



dialog function




function onChangeUpdate_order(_url) {

	

	 $('#dialogUpdateOrder').dialog('open');

	 var _updatePaymentComment_url;

     // If its a string then set the global variable, if its an object then don't set

    // if (typeof(_url)=='string')

             _updatePaymentComment_url=_url.value;


     jQuery.ajax({

             url: _updatePaymentComment_url,

             'data':$(this).serialize(),

             'type':'post',

             'dataType':'json',

             'success':function(data)

                     {

                             if (data.status == 'failure')

                             {

                            	 $('#dialogUpdateOrder div.divFormUpdate').html(data.div);

                                 // Here is the trick: on submit-> once again this function!

                           		$('#dialogUpdateOrder div.divFormUpdate form').submit(onChangeUpdate_order);

                             }

                             else

                             {

                            	 $('#dialogUpdateOrder div.divFormUpdate').html(data.div);

                                 setTimeout("$('#dialogUpdateOrder').dialog('close')",1000);

                             }


                     } 

             'cache':false

             });

     return false;


}



update controller




	public function actionUpdate($id)

	{

		

	if(isset($_POST['order_id']))

	

		$date=date('y-m-d');

		$model=$this->loadModel($id);

		

		

		$issave=false;

		$newproductissave=false;

		$orderdatilIsSave=false;

		$product=new Products();

		$orderdetail=OrderDetail::model()->findAll(array("condition"=>'order_id='.$_GET['id']));

		

		

		if(isset($_POST['oldproduct'])){//Update On old Products

			$newOrderdetail=new OrderDetail();

			

			$issave=true;

	

			//Create New product order of update panel

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

						

						$newproduct=$_POST['newproduct'];

						$newqty=$_POST['newqty'];

						$orderdetailmodel = new OrderDetail;

						$newproductissave=true;


	

						}

								

					}

			

		

		if(($issave)||($newproductissave)){

	

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

		                {

		                    echo CJSON::encode(array(

		                        'status'=>'success', 

		                        'div'=>"Order successfully updated"

		                        ));

		                    exit;               

		                }

		            else{

		

					$this->redirect(array('view','id'=>$model->order_id,'sql'=>$this->sql));

		            

		            }

			

			}

			

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

        {

            echo CJSON::encode(array(

                'status'=>'failure', 

                'div'=>$this->renderPartial('_form_update', array('model'=>$model,'orderdetail'=>$orderdetail,'product'=>$product), true)));

            exit;               

        }


	}



when i clicked on Edit menu, form is bind and dialog opened, and in firebug display message like this:

POST http://localhost:180/mobile_delivery_admin_2012_03_26/index.php/Order/Update/123

then i clicked on save button the post didn’t set and firebug display message like this:

[b]

POST http://localhost:180/mobile_delivery_admin_2012_03_26/

[/b]

why i had the problem when i save?

please give me any advices.

thanks.

I have one doubt to passing the parameters to an ajax link

			i have one image upload button ,if i click it shows the  local file folders,in that if we select the image without refreshing the page the url will change and only the image will show how do i do that through ajax link .

Thank u interboy.