Call js function from jQuery ajax callback

I’m a total newbie to ajax and jquery. I have got my first ajax sample working, but I have now run into a block.

I want to call a function from within a success function in an ajax call. But it always comes up with a js error "Object expected".

Here is the view code:

<script type="javascript">

function test(val) {

    alert('val = '+val);    



<?php echo CHtml::beginForm(); ?> 

<?php echo CHtml::label('Seed Number:','seed'); ?>

<?php echo CHtml::textField('seed',$seed,array('id'=>'seed','size'=>4,'maxlength'=>4)); ?>


Square: <span id="sq"><?php echo $sq; ?></span><br />

Square root: <span id="sqrt"><?php echo $sqrt; ?></span>


<?php echo CHtml::ajaxSubmitButton('Calculate',CController::createUrl('game/test'),


          'success'=>'function(data,status){ test("abc"); $("#sq").text(data.sq ); $("#sqrt").text(data.sqrt );}'));    



The call to test (‘test(“abc”);’) causes the problem.

How does one call a function like this?

this line:

 'success'=>'function(data,status){ test("abc"); $("#sq").text(data.sq ); $("#sqrt").text(data.sqrt );}')); 

should be

 'success'=>'js:function(data,status){ test("abc"); $("#sq").text(data.sq ); $("#sqrt").text(data.sqrt );}')); 

Thanks Pol.

I tried it, but still the same result: "Object expected". The page source is identical.

Are your controller rendering the result with json_encode?

Yes - it’s only the call to the js function test(). If that is removed it works just fine - even if I replace it with alert().

Here’s the controller:

    public function actionTest() {

        $seed = intval('0'.$_POST['seed']);

        if ($seed > 0) {

            $sq = pow($seed, 2);

            $sqrt = round(sqrt($seed), 3);


        else {

            $seed = 0;

            $sq = 0;

            $sqrt = 0;


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

            $json = CJavaScript::jsonEncode(array('sq'=>$sq,'sqrt'=>$sqrt));

            echo $json;





I’ve also tried to access a global variable, also with no success:

<script type="javascript">

var globalVar = "Global Var";



<?php echo CHtml::ajaxSubmitButton('Calculate',CController::createUrl('game/test'),


          'success'=>'function(data,status){ alert(globalVar); $("#sq").text(data.sq ); $("#sqrt").text(data.sqrt );}'));    


I’ve tried all sort of references to globalVar, such as document.globalVar, $(document).globalVar, $(this).parents(“document”).globalVar, etc, but no luck.

I could of course set and get the value of a hidden element but that does not help me wanting to execute common code external to the jQuery ready() function.

This has kept me busy for days: has anyone done this before?

I have solved the problem: I wrongly defined <script type="javascript"> instead of <script type="text/javascript">.