I have a Ajax request that fires on clicking a href that is part of a set of href’s having the same class .button. The HTML looks like this:
<div id="button-container">
<a href="#" class="button red" data-id="1"></a>
<a href="#" class="button red" data-id="2"></a>
<a href="#" class="button red" data-id="3"></a>
<a href="#" class="button red" data-id="4"></a>
</div>
Since, the href’s having the class .button are themselves loaded via a separate ajax call into the div #button-container and not available during page load, I am using jQuery on() to fire ajax call on clicking the .button href’s. The javascript looks like this:
jQuery('#button-container').on('click', '.button', function(e){
e.preventDefault();
var id = jQuery(this).data('id');
jQuery.ajax({
url: ajaxVars.ajaxurl,
type:'POST',
async: true,
cache: true,
timeout: 10000,
data: 'action=button_action&id=' + id,
success: function(value){
if (parseInt(value) == id) {
jQuery(this).removeClass('red').addClass('green');
} else {
jQuery(this).removeClass('green').addClass('red');
}
},
error: function() {
//alert(error);
}
});
});
The ajax fires as desired and I get a response from the server upon success. On success I need to toggle the class representing the color of href .button from .red to .green and vice-versa. This is where I have the issue. I get an error a.ownerDocument is undefined in the console. This appears to happen when removing the class. Also, I need to “only toggle the class of the clicked href”, hence I am using jQuery(this).
Any ideas on how to individually toggle the class of the href’s in above scenario?
Regards,
John
Inside your
.ajax()success callback,thisis not the anchor. You can force it to be the clicked anchor by passing acontextproperty as an option: