I’m using jQuery to cycle through a list of events and check a users attendance status. A simple ajax call using the rel value for event_id results in a result of either “0” or “1”.
If the attendance is positive (1) then I want to add a class of .selected to the link.
My calls seem to work and I can bring the results up in an alert, but for some reason the class isn’t being added when I try that.
Here is my HTML:
<a class="icon attend tip" href="#" title="RSVP Your Attendance" rel="59"></a>
Here is my jQuery:
$('a.attend').each(function(index) {
$.ajax({
url: '<?php echo site_url('ajax/event_attendance_status') ?>/' + $(this).attr('rel'),
success: function(data) {
if (data == '1') {
$(this).addClass('selected');
};
}
});
});
When you’re inside the callback function the context of the function differs from when you setup the request. Therefore, the this object refers to something else (in this case I think it’s the
XMLHttpRequestobject.)There are two ways of doing this. You could either save the
thisobject in another variable, and then use that variable to access the element, like so:An alternative, and frankly nicer and more elegant solution is to use the
jQuery.proxymethod to ensure the callback gets fired in the correct context.