Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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…

like image 800
mktums Avatar asked Jan 27 '13 11:01

mktums


1 Answers

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();
        }
    });
});
like image 139
Konstantin Dinev Avatar answered Oct 26 '22 14:10

Konstantin Dinev