Yii Framework Forum: Passing parameters to an ajax link - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Passing parameters to an ajax link Rate Topic: -----

#1 User is offline   Russell England 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 40
  • Joined: 10-March 11
  • Location:Stourbridge, UK

Posted 07 June 2011 - 09:29 AM

For creating new models in a form I use the excellent wiki article
http://www.yiiframew...eate-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
0

#2 User is offline   zaccaria 

  • Elite Member
  • PipPipPipPipPip
  • Yii
  • Group: Members
  • Posts: 2,232
  • Joined: 04-October 09
  • Location:Moscow

Posted 07 June 2011 - 09:36 AM

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!
1

#3 User is offline   Russell England 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 40
  • Joined: 10-March 11
  • Location:Stourbridge, UK

Posted 07 June 2011 - 10:09 AM

View Postzaccaria, on 07 June 2011 - 09:36 AM, said:

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
0

#4 User is offline   zaccaria 

  • Elite Member
  • PipPipPipPipPip
  • Yii
  • Group: Members
  • Posts: 2,232
  • Joined: 04-October 09
  • Location:Moscow

Posted 08 June 2011 - 01:07 AM

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 :)!
0

#5 User is offline   Russell England 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 40
  • Joined: 10-March 11
  • Location:Stourbridge, UK

Posted 08 June 2011 - 04:05 AM

View Postzaccaria, on 08 June 2011 - 01:07 AM, said:

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)
            ...





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?
0

#6 User is offline   Russell England 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 40
  • Joined: 10-March 11
  • Location:Stourbridge, UK

Posted 08 June 2011 - 05:29 AM

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
0

#7 User is offline   zaccaria 

  • Elite Member
  • PipPipPipPipPip
  • Yii
  • Group: Members
  • Posts: 2,232
  • Joined: 04-October 09
  • Location:Moscow

Posted 08 June 2011 - 08:36 AM

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
1

#8 User is offline   Russell England 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 40
  • Joined: 10-March 11
  • Location:Stourbridge, UK

Posted 08 June 2011 - 09:26 AM

View Postzaccaria, on 08 June 2011 - 08:36 AM, said:

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 :)
0

#9 User is offline   zaccaria 

  • Elite Member
  • PipPipPipPipPip
  • Yii
  • Group: Members
  • Posts: 2,232
  • Joined: 04-October 09
  • Location:Moscow

Posted 08 June 2011 - 09:43 AM

Cool, 100% cool
0

#10 User is offline   Asgaroth 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 371
  • Joined: 17-July 09
  • Location:Bogota, Colombia

Posted 08 June 2011 - 10:13 AM

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");

- Extension: Dynamic DataProvider Behavior
- Extension: XUpload - jQuery File Upload Extension
- Extension: PhpQuickProfiler - A Web Log Router that will help you profile your application
- Extension: XDateView - A Date grouped Grid View
- Extension: Foundation - An easy to use, powerful, and flexible framework for building prototypes and production code on any kind of device.



- Wiki: How to generate Yii like Documentation
- Wiki: How to re enable logging during unit testing
0

#11 User is offline   Russell England 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 40
  • Joined: 10-March 11
  • Location:Stourbridge, UK

Posted 08 June 2011 - 12:19 PM

View PostAsgaroth, on 08 June 2011 - 10:13 AM, said:

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.yiiframew...in-a-cgridview/
0

#12 User is offline   sakkona 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 9
  • Joined: 20-January 12

Posted 28 March 2012 - 05:02 AM

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...rder/Update/123

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

POST http://localhost:180...min_2012_03_26/


why i had the problem when i save?
please give me any advices.
thanks.
0

#13 User is offline   shobana_chandrasekar 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 51
  • Joined: 06-September 13
  • Location:Bangalore

Posted 05 October 2013 - 05:21 AM

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 .
0

#14 Guest_Interboy_*

  • Group: Guests

Posted 06 October 2013 - 12:00 PM

Hi,

Why don't use CHtml::ajaxLink();

public static string ajaxLink(string $text, mixed $url, array $ajaxOptions=array ( ), array $htmlOptions=array ( ))

See more examples of Ajax link

Example

echo CHtml::ajaxLink(
    $text = 'Click me', 
    $url = '/', 
    $ajaxOptions=array (
        'type'=>'POST',
        'dataType'=>'json',
        'success'=>'function(html){ jQuery("#your_id").html(html); }'
        ), 
    $htmlOptions=array ()
    );


Output:

<a href="#" id="yt0">Click me</a>

<script type="text/script">
    jQuery('body').on('click', '#yt0', function () {
        jQuery.ajax({
            'type': 'POST',
            'dataType': 'json',
            'success': function (html) {
                jQuery("#your_id").html(html);
            },
            'url': '/',
            'cache': false,
            'data': jQuery(this).parents("form").serialize()
        });
        return false;
    });
    });
</script>

0

#15 User is offline   shobana_chandrasekar 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 51
  • Joined: 06-September 13
  • Location:Bangalore

Posted 06 October 2013 - 04:35 PM

Thank u interboy.

View PostInterboy, on 06 October 2013 - 12:00 PM, said:

Hi,

Why don't use CHtml::ajaxLink();

public static string ajaxLink(string $text, mixed $url, array $ajaxOptions=array ( ), array $htmlOptions=array ( ))

See more examples of Ajax link

Example

echo CHtml::ajaxLink(
    $text = 'Click me', 
    $url = '/', 
    $ajaxOptions=array (
        'type'=>'POST',
        'dataType'=>'json',
        'success'=>'function(html){ jQuery("#your_id").html(html); }'
        ), 
    $htmlOptions=array ()
    );


Output:

<a href="#" id="yt0">Click me</a>

<script type="text/script">
    jQuery('body').on('click', '#yt0', function () {
        jQuery.ajax({
            'type': 'POST',
            'dataType': 'json',
            'success': function (html) {
                jQuery("#your_id").html(html);
            },
            'url': '/',
            'cache': false,
            'data': jQuery(this).parents("form").serialize()
        });
        return false;
    });
    });
</script>


0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

2 User(s) are reading this topic
0 members, 2 guests, 0 anonymous users