I have created an ajax link(CHTML::ajaxLink) in Yii framework(not ajax form submit button) that passes some value to a controller via ajax. There are multiple link which passes different value to the controller. I want to get the id/class attribute of the clicked link before the value is passed to the controller(in “beforeSend” of the jquery.ajax options ). Simply i just want to get the id/class attribute that generated the ajax request. Help!!!
UPDATE::Here’s the code
echo CHtml::ajaxLink ("Click Here",
Yii::app()->createUrl('default/del/id/6'),
array(
'beforeSend' => 'function(){
//I want to get the id of the link here
}',
'complete' => 'function(){
}',
'update' => '#loadContent'),
);
The above code will generate the following a tag:-
<a href="#" id="yt1">Click Here</a>
When the user click the above link, i want to get the id (yt1) in the beforeSend part of the
ajaxLink.
I tried the below code:
'beforeSend' => 'function(){
$("a").click(function(){
var a = $(this).attr("id");
alert(a);
}
The above code works but the id is alerted only when the link is clicked twice. On the third click, the id is alerted twice and keeps on increasing on subsequent clicks. I dont have any clue about this strange problem.
You can use
$.proxy(), to change the context of the function to anchor tag from the current ajax object:Edit:
Let me tell you why the number of alerts is growing on subsequent clicks.
This is happening because each time you click, there is a new click handler getting associated to the
<a>, because of this line:So when you click the first time, the order of function calls is:
So there is no alert yet.
Second time:
Third time:
And so on as it keeps increasing.
Edit2:
Alternative and better, you can use
contextoption to make the context, the link that was just clicked:From jquery’s ajax documentation:
Edit3:
Another alternative: Pass the id of link as an additional setting key: