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?
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.
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;
}
}
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