mktums mktums - 2 months ago 11
Javascript Question

jQuery remove element on ajax success

I have

<button>
with ajax on it, and want to remove it after successful request.

<script type="text/javascript">
$(".approve").click(function(){
var el, image_id = $(this).data('image-id');
$.ajax({
type: "PATCH",
dataType: "json",
data: { "approved": "True"},
url: "/ml/api/image/" + image_id + "/?format=json",
success: function(data){
$(this).remove();
}
});
});
</script>


But this doesn't work…

Answer

The context in the success callback is different from the context of the click event meaning this no longer refers to the button DOM element. Just select the button again and it would remove it:

$(".approve").click(function(){
    var el = $(this), image_id =  $(this).data('image-id');
    $.ajax({
        type: "PATCH",
        dataType: "json",
        data: { "approved": "True"},
        url: "/ml/api/image/" + image_id + "/?format=json",
        success: function(data){
            el.remove();
        }
    });
});
Comments