user1668543
user1668543

Reputation: 309

Hiding a div is not working properly in jQuery Ajax success

I have a jQuery script, in which I am going to hide the div after deleting that record. Here is the jQuery.

$(document).ready(function () {
    $(".deleteComment").click(function ()
     {
        alert("asd");

        var Id = $(this).attr("id");

        var url1 = "@Html.Raw(Url.Action("DeleteComment", "Comment", new { id = "idValue" }))";
        url1=url1.replace("idValue",Id );
        alert(url1);

        $.ajax(
        {
            type: 'post',
            url: '/Comment/DeleteComment',
            dataType: 'json',
            data:
            { 
              'EId' : Id    
            },
            success: function (data) 
            {
                alert ("Hello");
                var commentBlock = $(this).closest('div');
                commentBlock.hide('slow');                                   
            }                
        });

Problem is only in below code:

success: function (data) 
{
    alert ("Hello");
    var commentBlock = $(this).closest('div');
    commentBlock.hide('slow');
}

If I place above code at the beginning of script then it works fine. If I put in success then it fails.

Upvotes: 1

Views: 1792

Answers (1)

MikkoP
MikkoP

Reputation: 5092

this will refer to the ajax object as Igor mentioned and what he meant is this.

$(document).ready(function()) {
    var self = this;

    ...
    $.ajax(
        ...

        success: function(data) {
            $(self).closest("div").hide("slow");
        }
    );
}

Upvotes: 3

Related Questions