Reputation: 23989
I have an indicator on a page which is either a red or green circle.
<div class="publicBm changeState" currentstate="1" statusid="56" title="This is Public"></div> <!-- green -->
<div class="privateBm changeState" currentstate="1" statusid="57" title="This is Private"></div> <!-- red -->
When a user clicks the circle (which is a div with class changeState as shown above) an AJAX call is made to update the database to the opposite of what the item currently is, public or private. Then it returns the opposite class.
All works perfectly but I want to change the class on the circle clicked to reflect that the update has been successful.
Here's what I'm trying - as I said, the actual database call within the php file is perfect it's just that the div is not having it's class changed.
NOTE - there can be multiple lines on each page so I can't simply give the DIV an id
$('.changeState').click(function() {
var bm_id = $(this).attr('statusID');
var current = $(this).attr('currentState');
$.ajax({
type: "POST",
url: '/ajax/actions/editStateBm.php?bm_id='+bm_id+'¤t='+current,
success:
function(data) {
$(this).removeAttr('class').attr('class', data + ' changeState');
}
});
});
Upvotes: 0
Views: 100
Reputation: 123739
Your issue is this
. this
is not the DOM element inside the ajax success callback. Instead set the context as that of the element so that this
inside the callback now refers to the element and not jqXhr object.
$.ajax({
type: "POST",
url: '/ajax/actions/editStateBm.php?bm_id='+bm_id+'¤t='+current,
context: this, //<-- Here
success:
function(data) {
this.className = data + ' changeState';
}
});
or use a cached context.
...
var self = this;
$.ajax({
type: "POST",
url: '/ajax/actions/editStateBm.php?bm_id='+bm_id+'¤t='+current,
success:
function(data) {
self.className = data + ' changeState';
}
});
...
BTW what are you posting? you need to use GET
?
$.ajax({
type: "GET",
....
Upvotes: 1
Reputation: 3662
This should be something like:
$(this).removeClass('class').addClass(data + ' changeState');
Upvotes: 0
Reputation: 57095
Use .addClass()
success: function (data) {
$(this).removeAttr('class').addClass(data + ' changeState');
}
and removeProp
success: function (data) {
$(this).removeProp('class').addClass(data + ' changeState');
}
Upvotes: 1