Element in success callback

Hi good people,

I wonder if u could help me with a little lets say yii jquery thing ;)

The code is something like:

echo CHtml::imageButton( 'my button',


              'ajax' => array(


                'url'=> ...,


                'success' => "function()


                  addToBasket( {$model->id} );





My question is: how can I get the clikced element within the success callback function?

Obviously I need that element in addToBasket function. Ofcourse I can pass the unique id of this element there, but I have a large ammount of such elements, I dont want each of them to have their ids. Is there a better way? In pure jquery its not a problem, cause I have clicked element being stored in ‘this’ object while setting click event. Any suggestions?

thanks, Jan

The $(this) object should work here too

imageButton is just a helper that generates HTML code… check the resulting page source code and take a look where is placed the ajax call…

I think $( this ) object represent the ajax object here. Thats why

alert( $( this ).attr( 'type' ) );

gives ‘get’ as an output. Or am I missing something? To the imagebutton must be added click event somewhere, there is a place, where $( this ) represents needed element. I need to know ( within my success function ) which element have fired the ajax call.

You are right…

I don’t see an easy way to get the parent here… other than using an id…

you said that you don’t want all those element to have their ids,

but they already have id autogenerated (like yt0, yt1, …), so it’s not an big issue to give them a custom one

In my applications i use classes to mark elements with behaviors and also save IDs in classes. This plays very nicely with jQuery. In your case i’d do something like:

<?php echo CHtml::button('Add to Basket',array('class'=>'button-add-to-basket id'.$model->id)); ?>

This way you can create such a button very easily everywhere you need it: Add a class and you’re done. You’ll need one single js event handler for all these buttons:

$('.button-add-to-basket').live('click',function() {

    var id=myLib.getIdFromClass($(this));

    $.ajax({ ... });

    return false;


The live() method makes sure, that even if you replace the grid content, all buttons will still work.

You’ll need some little javascript helper on the clientside. I’ve created my custom js module for it. But you could use something simple as:

var myLib={

    getIdFromClass : function(e) {

        var r= /\bid(\d+)/.exec($(e).attr('class'));

        if (r && r.length>1)

            return r[1];

        return null;



Maybe you get the basic idea.

Thank you guys. Just wanted to make sure, that I dont miss anything, cause I want to make current project as much Yii-style as possible. So far so good :)

cheers, Jan