Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent loading of jQuery assets with ajaxButton/ajaxSubmitButton on Yii framework

I have jQuery load asset on my layout and I want to use CHtml::ajaxButton/ajaxSubmitButton. But when I'm using it with another render on runtime it's loading jQuery assets again and makes an error. How to prevent the script from loading?

<?php echo CHtml::ajaxSubmitButton( 'Submit',
                                        CHtml::normalizeUrl(array('site/AjaxRequest/30')),
                                        array(
                                        'error'=>'js:function(){
                                            alert(\'error\');
                                        }',
                                        'beforeSend'=>'js:function(){
                                            alert(\'beforeSend\');
                                        }',
                                        'success'=>'js:function(data){
                                            alert(\'data from server: \'+data);
                                        }',
                                        'complete'=>'js:function(){
                                            alert(\'complete\');
                                        }',
                                        //'update'=>'#response',
                                        )
                                    );
    ?>
like image 866
Dar Avatar asked Dec 09 '22 23:12

Dar


1 Answers

This is a pretty annoying issue IMO as well. The way I solved is to create a derived class of CClientScript and use that as the clientScript component (you can override the class type in your config file):

'clientScript' => array
(
    'class'                       => 'MyClientScript',
),

My class overrides the "registerCoreScript" function, which is used for registering jQuery and other basic scripts that Yii includes. Pretty much what I do in there is add a check for ajax and not pass it on to the parent class if it is. It looks something like this:

public function registerCoreScript($sName)
{
   if (Yii::app()->request->isAjaxRequest)
      return $this;

   return parent::registerCoreScript($sName);
}

This prevents any core script being loaded (and adding assets again) during an ajax call.

You can do the same for other functions in there too (eg registerScriptFile)

Hope that helps.

like image 123
Blizz Avatar answered May 07 '23 04:05

Blizz