jquery + ajax replace class -
i trying replace button class ajax, wrong?
my button:
<input type="button" class="btn btn-default btn-sm addlike" name="{{ answer.pk }}" value="like" ></input>
my js:
$('.addlike').click(function(){ $.ajax({ type: "post", url: "{% url 'add_like' %}", data: {'answer_pk': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, datatype: 'json', success: function(response){ alert(response.message); if ( $(this).hasclass('btn-default')) { $(this).removeclass('btn-default').addclass('btn-success'); } else if ($(this).hasclass('btn-success')) { $(this).removeclass('btn-success').addclass('btn-default'); } } }); })
message, it's test alert message django view function. problem replace element
inside callback, $(this)
refers jqxhr
object of ajax call, not element event handler bound to.
try doing this.
$('.addlike').click(function() { var element = this; // adding current object in variable $.ajax({ type: "post", url: "{% url 'add_like' %}", data: { 'answer_pk': $(element).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}' }, datatype: 'json', success: function(response) { alert(response.message); if ($(element).hasclass('btn-default')) { $(element).removeclass('btn-default').addclass('btn-success'); } else if ($(element).hasclass('btn-success')) { $(element).removeclass('btn-success').addclass('btn-default'); } } }); });
hope helps.
Comments
Post a Comment