ajaxLink. How to trigger error?

I use ajaxLink to create link which must run actionUpdate() function in my controller.


echo CHtml::ajaxLink('Update data', '/data/update', array(

    'success'=>'function(data) { alert("success"); }',          

    'error'=>'function(data) { alert("error"); }'));

In my controller’s action I do some work. On success it must return some data, and on error it must trigger error and ajax error function must be run (alert(“error”)).


public function actionUpdate()

{

   ... do some work ...

   if (... ok ...)

      echo 'Data updated';

   else

      <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/huh.gif' class='bbc_emoticon' alt='???' />?

}

But what should I return from my function to trigger ajax error function (function(data){alert("error");}) ??


sorry for my english

I’m not sure… .but I think you cannot triger the ajax error function… that is called if some error happens during the ajax call (wrong url for example)…

So for your case you can return some special value, like -1… then in your success function check for that value and display the alert(‘error’);

Mdomba is right, thats the way you do it

Take a look at this wiki.

Here I return a json encoded array, with a status and some data to use according to statuses.

Thanks, mdomba. I will use something like return -1 and then if (data == "-1") alert("error").

One more question. I need to pass to javascript ‘success’ function 3 numbers. I generate this numbers in my function in controller (actionUpdate()). How could I pass 3 numbers to ajax’s ‘success’ function?

May be I need just something like this:

public function actionUpdate()

{

echo "43.23|4532.3|32"; // send 3 numbers separated by |

}

And in ‘success’ function I will parse it (data variable) by splitting this numbers by character “|”. Is it correct solution?

using json

php


echo json_encode(array('success'=>'1','message'=>'success!!!','3rd parameter'));

Yii::app()->end();;

js




success:function(data){

   if(data.success===1){

    	alert(data.message);

   }

}