Question

i am trying to call a function which is defined in another js file by afterAjaxUpdate paramter of the file name but i got error in console that function is not defined

<?php 
$dataProvider=new CActiveDataProvider('profiles',array('pagination'=>array('pageSize'=>3))); ?>
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_profilesview',
'template'=>'{sorter}<br />{pager}{items}{pager}',
    'enableSorting' => true,
    'sortableAttributes'=>array(
     'name'=>'By firstName',
     'location'=>'By city',
     'age'=>'By age',
     'likes'=>'By likes'
     ),
     'afterAjaxUpdate'=>'readcookie()',
));
 ?>

my js function is

$(document).ready(function(){
   function readcookie()
   {
       alert("hi");
   }
});

i can see in my source that function defined in the file is included after all the js files that are included by yii default when i register my script in my layout it dosent find $ because jquery not included when i include jquery it gets included twice which leads to trigger my event i also tried to by setting

renderPartial('Mybelowview',null,false,true)

which leads again my js file to include multiple times and my event gots trigger multiple time.

This is very confusing please help to get out of it Thanks all for being so generous

Was it helpful?

Solution

The problem is that functions inside $(document).ready(); are out of scope outside of it, and that's why you get undefined. So you can either just have:

// $(document).ready(function(){
   function readcookie()
   {
       alert("hi");
   }
// });
// omit document.ready to make function available in the global scope

or define the function on the window object to make it global:

$(document).ready(function(){
   window.readcookie=function ()
   {
       alert("hi");
   };
});

Lastly define the attribute 'afterAjaxUpdate' as :

'afterAjaxUpdate'=>'readcookie'
// if it is readcookie() it becomes a function call instead
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top